如何检查NSData blob是否有效作为NSURLSessionDownloadTask的resumeData?

Ian*_*ell 10 ios ios7 nsurlsession nsurlsessiondownloadtask

我有一个使用新NSURLSessionAPI 下载后台的应用程序.当下载以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.
Run Code Online (Sandbox Code Playgroud)

这里出现的错误,这里resumeDataNSDatablob和session是一个实例NSURLSession:

if (resumeData) {
    downloadTask = [session downloadTaskWithResumeData:resumeData];
    ...
Run Code Online (Sandbox Code Playgroud)

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

如何提前检查resumeData无效,以免我让应用程序崩溃?

rus*_*elf 25

这是Apple建议的解决方法:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

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

  • 来源是我和Apple工程师之间的Twitter交流.这是他的最后一条推文:https://twitter.com/atnan/status/431571791799005184 (2认同)