如果无法使用 NSURLSession 下载文件,iOS::error 为零

标签 ios objective-c ios8 nsurlsession

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

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/

相关文章:

ios - TestFlight 中缺少合规性状态

ios - NSFetchedResultsController performFetch 函数解码所有对象

ios - 为 CellIdentifier 使用静态 NSString 有什么好处?

ios - iOS 上的 Unity3D,在 Obj-C 中检查设备相机图像

objective-c - prefix 属性后面必须跟一个接口(interface)或协议(protocol)栈溢出

ios - 设置 contentInset 并且 tableViewHeader 中的 UITextField 变为事件状态时 UITableView 向下滚动

ios - 更新 iOS 8 应用程序

ios - 在 Xcode 7、iOS 9 "Application windows are expected to have a root view controller at the end of application launch"

objective-c - 在 Objective-C 类中导入 Swift 协议(protocol)

uiviewcontroller - iOS 8 : Presenting a modal view controller in portrait causes resize of the navigation bar of the underlying landscape navigation controller