gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:25:54 26 4
gpt4 key购买 nike

我正在使用 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 意义上的错误。这是一个完全合法的响应,因此您不会期望在 error 中出现任何内容。

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

请注意,您收到了一个 NSURLResponse。您可能需要将其转换为 NSHTTPURLResponse 才能访问其 statusCode

关于如果无法使用 NSURLSession 下载文件,iOS::error 为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31517673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com