我是iOS编程的新手。在我的测试应用程序中,我想从服务器下载一些xml数据并从中进行一些注释。它工作的很好,作为下一步,我通过调度将它改为异步。在IOS5下异步下载数据时处理错误
一切正常,但我不知道如何处理这种情况下的异常?如果服务器不可用,在哪里/如何处理?在没有网络连接的情况下/如何处理?在哪里/如何处理连接超时?
我的测试代码如下所示:
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);
特撷取的getTestData方法的最相关的部分提前
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];
谢谢!
有第三方HTTP客户端库,使所有这些微不足道。 AFNetworking似乎是一种流行的选择(我以前最喜欢的,ASIHTTPRequest最近已弃用)。 – 2012-01-17 18:09:07