gpt4 book ai didi

ios - NSURLSessionDownloadTask 偶尔会导致 nil 数据

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

我在我的应用程序中(在 UICollectionView 中)从 CDN 异步下载图像。每次我运行它时,不同的图像将无法加载。 22 个中大约有 1-3 个。有时(很少)它们都会加载。但关键是它不一致。发生的事情是在这一行中:

NSData *fileData = [NSData dataWithContentsOfURL:location];

fileData 间歇性地为 nil 。奇怪的是,NSURLSessionDownloadTask 中的error 也是nil。这是完整的方法:

+ (void) downloadFileAsynchronouslyWithUrl:(NSURL *)fileUrl andCallback:(void (^)(NSData* fileData, NSError* error))callback {
NSURLSessionDownloadTask *downloadTask = [[NSURLSession sharedSession] downloadTaskWithURL:fileUrl completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error != nil) {
NSLog(@"ERROR: %@", error.localizedDescription);
callback(nil, error);
}
else {
NSData *fileData = [NSData dataWithContentsOfURL:location];
if (fileData != nil) {
callback(fileData, nil);
}
else {
// Getting this intermittently
NSError *err = [self errorFromString:@"downloaded file was nil!"];
callback(nil, err);
}
}
});
}];
[downloadTask resume];
}

我记录了状态码,一直是200。

令我困惑的是什么会导致这种情况。有什么想法吗?

最佳答案

您应该确保将文件同步移动到本地(或将其加载到 NSData)。当您从此 downloadTaskWithURL 完成 block 返回时,文件将被删除。你正试图从 dispatch_async 中读取这个文件,这在从文件中获取数据和操作系统为你删除这个临时文件之间引入了竞争条件。

所以,你可以尝试这样的事情:

+ (void) downloadFileAsynchronouslyWithUrl:(NSURL *)fileUrl andCallback:(void (^)(NSData* fileData, NSError* error))callback {
NSURLSessionDownloadTask *downloadTask = [[NSURLSession sharedSession] downloadTaskWithURL:fileUrl completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error != nil) {
NSLog(@"ERROR: %@", error.localizedDescription);
dispatch_async(dispatch_get_main_queue(), ^{
callback(nil, error);
});
}
else {
NSData *fileData = [NSData dataWithContentsOfURL:location];
dispatch_async(dispatch_get_main_queue(), ^{
if (fileData != nil) {
callback(fileData, nil);
}
else {
// Getting this intermittently
NSError *err = [self errorFromString:@"downloaded file was nil!"];
callback(nil, err);
}
});
}
}];
[downloadTask resume];
}

或者,您可以考虑使用 URLSessionDataTask,它可以避免这个问题。当我们试图减少峰值内存使用和/或使用后台 session 时,我们通常会使用下载任务,但这两种情况都不适用于此处。

关于ios - NSURLSessionDownloadTask 偶尔会导致 nil 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48217076/

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