I am a rookie in iOS programming. In my test app I’d like to download some xml data from a server and make some annotations from it. It works great, and as a next step I changed it to be asynchronous by dispatching.
Everything works great, but I don’t know how to handle exceptions in this scenario? Where/how to handle if the server is unavailable? Where/how to handle if there is no network connection? Where/how to handle connection time outs?
My test code looks like this:
dispatch_queue_t downloadQueue = dispatch_queue_create("test data fetcher", NULL);
dispatch_async(downloadQueue, ^{
NSString* fetchedXML = [Fetcher getTestData:@"http://127.0.0.1:11111"];
dispatch_async(dispatch_get_main_queue(), ^{
NSArray *annotations = [TestAnnotation getFromXML:fetchedXML];
self.annotations = annotations;
});
});
dispatch_release(downloadQueue);
Te most relevant part of Fetcher’s getTestData method
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
Thanks in advance!
You are passing an NSURLResponse and NSError by reference to the sendSynchronous selector of NSURLConnection. When this selector returns, those objects will be populated with the data you are after.
1) Instead of passing NSURLResponse, pass NSHTTPURLResponse, which is a subclass that will allow you to inspect the HTTP status code (response.statusCode) for non-200 codes.
2) Check to see if the return value from sendSynchronous is nil and inspect the NSError object for information about the error condition. This is where timeouts and other connectivity issues will appear.