iOS :: 如果无法使用 NSURLSession 下载文件,则错误为 nil

iOS :: error is nil if not able to download file with NSURLSession

我正在使用 NSURLSessionNSURLSessionTask 在应用程序中下载文件。如果文件存在于服务器上,那么它工作正常。如果文件不可用,那么它将数据写入文件并且不下载它。 例如 :: 如果文件不可用,它会写

Access is denied

在文件中并完成任务,没有任何错误。在这种情况下,错误为 nil。

但我想向用户显示警告框,提示文件不可用。

下面是代码...

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 块。

我厌倦了把这个放在 try catch block 然后也没有运气。

如何处理 iOS 中的此类错误?

我假设服务器正在返回诸如 401(未经授权)之类的响应代码,以及诸如 "Access is denied." 之类的正文。这不是 NSURLSession 意义上的错误。这是一个完全合法的回应,因此您不会期望 error.

中有任何内容

相反,您需要检查响应的 statusCode 值。这应该在 200-299 之间才能成功。正如我所说,您可能收到 401。

请注意,您已通过 NSURLResponse。您可能需要将其转换为 NSHTTPURLResponse 才能访问其 statusCode.

您正在使用 dataTaskWithURL: 下载图像。对于下载任务,您应该使用 downloadTaskWithURL:.

[[session downloadTaskWithURL:[NSURL URLWithString:[S3_SERVER_URL stringByAppendingString:propFile]] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error)
{
    if (error)
    {
        // Show error
    }
    else
    {
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:propfilePath] error:nil];
    }
}] resume];

更多详情请参考:

  1. NSURLSessionDownloadTask
  2. NSURLSessionDataTask

使用以下代码获取 httpresponse 状态代码。

NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
            NSLog(@"response status code: %ld", (long)[httpResponse statusCode]);