How to test if a web service is available
I am retrieving data from a web service with...
NSString *myDataString = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&outError];
How can I handle a situation where the web service is not available? As it is now the app simply hangs up.
Is there a way to test if a site is available? olso, initWithContentsOfURL does not have any time out functionality.
I looked at using URLConnection as an altern开发者_运维问答ative way to request and receive the data string. I could not, however, figure out how.
Thanks for any help.
John
You shouldn't use initWithContentsOfURL:
, it is a blocking API and will cause your app to hang while it executes, unless you manually spawn a new thread to run it on and manage it properly.
You should use NSURLConnection
to perform web requests.
Using NSURLConnection
you will get a non-blocking, asynchronous functionality, and will also be able to handle things like authentication, response codes, time-outs and cancelling the request.
Look up the documentation for NSURLConnection
, and NSURLRequest
(and also NSMutableURLRequest
).
The NSURLConnection
delegate methods are how you will handle response codes, authentication, etc.
As for your original question, you can test the availbility of the webservice in a number of ways:
- Use Apple's Reachability example to test whether the internet connection and/or host is reachable from your current network.
- Use
NSURLConnection
to handle the response codes from the server. 200 is OK, 404 Page not found, 401 authorization required, 500 internal server error, etc, etc, etc- You can perform different actions depending on the code.
精彩评论