我正在使用 NSURLSession
和 NSURLSessionTask
在应用程序中下载文件。如果服务器上存在文件,则它可以正常工作。如果文件不可用,则它将数据写入文件但不下载它。
例如::如果文件不可用,它会写入
Access is denied
在文件中并完成任务,没有任何错误。在这种情况下,错误为零。
但我想向用户显示警告框,指出文件不可用。
下面是代码...
task1 = [session dataTaskWithURL:[NSURL URLWithString:[S3_SERVER_URL stringByAppendingString:propFile]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
propfilePath = [[Util getInAppTempPath] stringByAppendingString:propFile];
NSLog(@"DestPath : %@", propfilePath);
[receivedData appendData:data];
NSLog(@"Succeeded! Received %lu bytes of data",(unsigned long)[data length]);
//[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[data writeToFile:propfilePath atomically:YES];
//NSLog(@"iOSDBVersion: %@", [plistDictionary objectForKey:@"iOSDBVersion"]);
//NSLog(@"ttodDBVersion: %@", [plistDictionary objectForKey:@"ttodDBVersion"]);
if(error == nil){
[Util getDataFromPlistFile];
[Util isAppRunBefore];
[self downloadDatabase];
} else {
[self alertNoPlist];
}
}];
[task1 resume];
它永远不会进入 else block 。
我厌倦了把它放在try catch block
中,但也没有运气。
如何在 iOS 中处理此类错误?
最佳答案
我假设服务器返回诸如 401(未经授权)之类的响应代码,以及诸如“访问被拒绝”之类的正文。从 NSURLSession
意义上来说,这不是一个错误。这是一个完全合法的响应,因此您不会期望出现任何错误
。
相反,您需要检查响应的 statusCode
值。成功的值应该在 200-299 之间。正如我所说,您可能会收到 401。
请注意,您已传递了一个 NSURLResponse
。您可能需要将其转换为 NSHTTPURLResponse
才能访问其 statusCode
。
关于如果无法使用 NSURLSession 下载文件,iOS::error 为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31517673/