我的应用程序中所有与服务器的连接都是相同的:
- dispatch_async to a 2nd thread.
- sendSynchronousRequest
fail/success blocks on main thread.
The following is not the full code, just the concept:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSURL *url = [NSURL URLWithString:@"someURL"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; NSURLResponse *response = nil; NSError *error; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (error) { dispatch_async(dispatch_get_main_queue(), ^{ _failureBlock(error); }); } else { dispatch_async(dispatch_get_main_queue(), ^{ _successBlock(data); }); });
这个应用程序非常好用!我可以用它连接数千台服务器,并且每次启动应用程序时都能正常运行。
问题出现在以下情况:
- 将应用程序发送到后台。
- 等待一段时间...
- iOS终止了应用程序。
- 再次打开应用程序时,iOS会完全重新加载整个应用程序。 (看到启动画面,然后是第一个屏幕,而不是我离开时的屏幕。)
在这种情况下,我会遇到NSURLConnectionErrors!!各种各样的错误!代码1003、代码1009、代码9...什么都有!我会得到所有从应用程序启动开始的服务器连接错误。之后的任何其他连接都正常工作!包括刷新失败的那些连接!
这几乎感觉像是我尝试过早或过快地访问我的服务器,但是在发起连接之前,我确实检查并通过了可达性测试。
真的需要一些帮助。 提前致谢。
更新:如下所建议,尝试使用sendAsynchronousRequest - 但出现了完全相同的行为。(这次是err:1001)