在iOS8上运行时dataWithContentsOfURL崩溃

时间:2014-10-09 08:42:01

标签: ios iphone ios8

当主机无法访问并且有互联网连接时,

dataWithContentsOfURL在iOS8上崩溃。

NSURL *url = [NSURL URLWithString:myurl];

    @try {
        data = [NSData dataWithContentsOfURL:url];
    }
    @catch (NSException *exception) {
        data = nil;
    }
    if(data!=nil){
        [data writeToFile:filePath atomically:YES];
    }else{
        data = [NSData dataWithContentsOfFile:filePath];
        if (data==nil) {
            return nil;

        }
    }

1 个答案:

答案 0 :(得分:0)

来自文档:

Important: Do not use this synchronous method to request network-based URLs.
For network-based URLs, this method can block the current thread for tens of
seconds on a slow network, resulting in a poor user experience, and in iOS,
may cause your app to be terminated.

如果您需要了解失败的原因,请使用 dataWithContentsOfURL:options:error:

相反,对于非文件网址,请考虑使用NSSession类的 dataTaskWithURL:completionHandler: 方法。