How can I check that an NSData blob is valid as resumeData for an NSURLSessionDownloadTask?

后端 未结 3 655
时光取名叫无心
时光取名叫无心 2020-12-23 23:33

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 NSURLSessionDownloadT

相关标签:
3条回答
  • 2020-12-24 00:10

    actually, the resume data is a plist file. it contains the follows key:

    • NSURLSessionDownloadURL
    • NSURLSessionResumeBytesReceived
    • NSURLSessionResumeCurrentRequest
    • NSURLSessionResumeEntityTag
    • NSURLSessionResumeInfoTempFileName
    • NSURLSessionResumeInfoVersion
    • NSURLSessionResumeOriginalRequest
    • NSURLSessionResumeServerDownloadDate so the steps u need to do are:

      1. check the data is a valid plist;
      2. check the plist have keys as above;
      3. check the temp file is exist;
    0 讨论(0)
  • 2020-12-24 00:25

    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];
    }
    

    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

    0 讨论(0)
  • 2020-12-24 00:31

    I have not found an answer to how to tell if the data is valid ahead of time.

    However, I am presently working around the issue like so:

    NSData *resumeData = ...;
    NSURLRequest *originalURLRequest = ...;
    NSURLSessionDownloadTask *downloadTask = nil;
    
    @try {
        downloadTask = [session downloadTaskWithResumeData:resumeData];
    }
    @catch (NSException *exception) {
        if ([NSInvalidArgumentException isEqualToString:exception.name]) {
            downloadTask = [session downloadTaskWithRequest:originalURLRequest];
        } else {
            @throw exception; // only swallow NSInvalidArgumentException for resumeData
        }
    }
    
    0 讨论(0)
提交回复
热议问题