我有一个使用新版本的后台下载的应用程序NSURLSession
蜜蜂。当下载取消或失败时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
is the NSData
斑点和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):我从与一位 Apple 工程师的 Twitter 交流中得到了这个,他建议了该怎么做,我写了上面的实现
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)