IOS5下异步下载数据时的错误处理
我是iOS编程的菜鸟。在我的测试应用程序中,我想从服务器下载一些 xml 数据并从中进行一些注释。它工作得很好,下一步我通过调度将其更改为异步。
一切都很好,但我不知道如何处理这种情况下的异常?如果服务器不可用,在哪里/如何处理?如果没有网络连接,在哪里/如何处理?在哪里/如何处理连接超时?
我的测试代码如下所示:
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);
Fetcher 的 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];
提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在通过引用 NSURLConnection 的 sendSynchronous 选择器来传递 NSURLResponse 和 NSError 。当此选择器返回时,这些对象将填充您想要的数据。
1) 不要传递 NSURLResponse,而是传递 NSHTTPURLResponse,它是一个子类,允许您检查 HTTP 状态代码 (response.statusCode) 中是否有非 200 代码。
2) 检查 sendSynchronous 的返回值是否为 nil,并检查 NSError 对象以获取有关错误情况的信息。这是会出现超时和其他连接问题的地方。
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.
好吧,虽然这与您的问题没有直接关系,但您可能会考虑使用 NSURLConnection 的内置异步请求设施,而不是使用 +sendAsynchronousRequest:queue:completionHandler: 或 – initWithRequest:delegate: 来使用dispatch_async() 滚动自己的设施。
在您的情况下,从方法文档中:
“如果无法创建连接或下载失败,则返回 nil。”
因此,您可能会遇到这样的习惯用法:
关于此问题(以及传入 NSError ** 的所有其他情况),要记住的主要事情是您永远首先读取错误值以查看是否存在失败发生了。您仅在被告知(在本例中,responseData 为零)出现错误情况后才检查它。
PS- 在 Objective-C 中,“异常”专指程序员错误,因此使用“异常”来描述网络故障是不正确的。这只是一个运行时错误,预计会在正常业务过程中处理。
Well, while this isn't directly related to your question, you might consider using NSURLConnection's built-in asynchronous request facilities rather than rolling your own with dispatch_async(), using either +sendAsynchronousRequest:queue:completionHandler: or – initWithRequest:delegate:.
In your case, from the method documentation:
"Returns nil if a connection could not be created or if the download fails."
So, you would have an idiom such as:
The main thing to remember about this (and all other cases where NSError ** is passed in) is that you never read the error value first to see whether a failure happened. You only inspect it after being told (in this case, by having nil responseData) that an error condition has arisen.
P.S.- In Objective-C, "exception" specifically refers to programmer error, so the use of "exception" to describe a network failure is incorrect. That would just be a run-time error expected to be handled in the ordinary course of business.