views:

182

answers:

1

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 alternative way to request and receive the data string. I could not, however, figure out how.

Thanks for any help.

John

+2  A: 

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.
Jasarien
Thanks. I think I am on the right track now, but I am confused by the Reachability stuff. The SCNetworkReachability flags only tell you about the device's connection to the network. It tells you nothing about the availability of an outside host.In the iPhone Developer's Cookbook there are 2 listings that to me do exactly the same thing...connectedToNetwork (pg305)hostAvailable (pg 307)The second method will only return NO if I physically disconnect the device from the network.I don't see what use the second method is if the first does the same thing.Thanks again for your help.
Apple's reachability example has methods to check the reachability of a particular host. I use it in my own apps. I use `[Reachability reachabilityWithHostName:@"apple.com"];` which returns a new reachability instance that will monitor the hostname provided.
Jasarien