当主机无法访问时,NSString stringWithContentsOfURL 会使应用程序崩溃
这确实是一个棘手的问题,我使用如下代码:
NSError *error = nil;
NSString *guideText = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
除非我将 URL 指向的服务器拉下来,否则代码就像一个魅力。它发出大约 1 分钟的暂停,但随后方法调用返回并出现错误。到目前为止,一切都很好。当我在模拟器中或在调试器下的设备上运行应用程序时,它的行为方式相同。但是,如果我在没有调试器的设备上运行该程序,它会在暂停后崩溃。我尝试将代码包装在 @try/@catch 中,但没有任何帮助。实际上调试器没有看到任何问题,所以这对我来说有些神秘。我尝试添加一些保护代码,如下所示:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
if ([NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil])
// here code above
[request release];
该代码的行为与以前完全相同。程序在此暂停一分钟,然后正常运行,除非它在没有调试器的设备上运行。
It is really tricky problem, I use code as below:
NSError *error = nil;
NSString *guideText = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
The code works like a charm unless I bring server which URL points down. It issues about 1 minute pause, but then the method call returns with an error. So far so good. It behaves same way when I run app in simulator or on device under debugger. But if I run the program on device without debugger, it crashes after the pause. I tried wrap the code in @try/@catch, but nothing helps. Actually debugger doesn't see any problems, so here is some mystery for me. I tried to put some guard code as below:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
if ([NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil])
// here code above
[request release];
The code behaves exactly as previous. Program pauses here for a minute and then goes through normally, unless it runs on device without debugger.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论