如何检查NSData blob是否有效作为NSURLSessionDownloadTask的resumeData? [英] How can I check that an NSData blob is valid as resumeData for an NSURLSessionDownloadTask?

查看:285
本文介绍了如何检查NSData blob是否有效作为NSURLSessionDownloadTask的resumeData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序使用新的 NSURLSession API进行后台下载。当下载以提供 NSURLSessionDownloadTaskResumeData 的方式取消或失败时,我存储数据blob以便以后可以恢复。我注意到在野外崩溃的时间非常少:

I have an app that's using background downloads with the new NSURLSession APIs. When a download cancels or fails in such a way that NSURLSessionDownloadTaskResumeData is provided, I store the data blob so that it can be resumed later. A very small amount of the time I am noticing a crash in the wild:

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和会话 NSURLSession 的实例:

The error occurs here, where resumeData is the NSData blob and session is an instance of NSURLSession:

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

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

The data is provided by the Apple APIs, is serialized, and is then deserialized at a later point in time. It may be corrupted, but it is never nil (as the if statement checks).

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

How can I check ahead of time that the resumeData is invalid so that I do not let the app crash?

推荐答案

这是Apple建议的解决方法:

This is the workaround suggested by 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];
}

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

Edit (iOS 7.1 is not NDA'd anymore): I got this from a Twitter exchange with an Apple engineer, he suggested what to do, and I wrote the above implementation

这篇关于如何检查NSData blob是否有效作为NSURLSessionDownloadTask的resumeData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆