ios – 如何检查一个NSData blob是否作为NSDataSessionDownloadTask的resumeData有效?

我有一个应用程序,使用后台下载与新的NSURLSession API.当下载取消或以提供NSURLSessionDownloadTaskResumeData的方式失败时,我存储数据blob,以便稍后恢复.很少的时候,我注意到在野外的崩溃:
Fatal Exception: NSInvalidArgumentException
Invalid resume data for background download. Background downloads must use http or https and must download to an accessible file.

这里出现错误,其中resumeData是NSData blob,session是NSURLSession的一个实例:

if (resumeData) {
    downloadTask = [session downloadTaskWithResumeData:resumeData];
    ...

数据由Apple API提供,序列化,然后在稍后的时间点进行反序列化.它可能已损坏,但它永远不会为零(如if语句检查).

我如何提前检查一下resumeData是无效的,以免我的应用崩溃?

解决方法

这是苹果建议的解决方法:
- (BOOL)__isValidResumeData:(NSData *)data{
    if (!data || [data length] < 1) return NO;

    NSError *error;
    NSDictionary *resumeDictionary = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:NULL error:&error];
    if (!resumeDictionary || error) return NO;

    NSString *localFilePath = [resumeDictionary objectForKey:@"NSURLSessionResumeInfoLocalPath"];
    if ([localFilePath length] < 1) return NO;

    return [[NSFileManager defaultManager] fileExistsAtPath:localFilePath];
}

编辑(iOS 7.1不再是NDA):我从与苹果工程师的Twitter交流中获得了这一点,他建议做什么,我写了上面的实现

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...