在读取内容之前删除了NSURLSessionDownloadTask文件

时间:2016-11-23 13:30:41

标签: ios nsurlsessiondownloadtask

我有以下代码已经工作了几个月,并且刚刚开始间歇性地破解。

我正在改变它被调用的方式,所以它并不完全不足为奇,但症状令我感到困惑。某些请求正在下载的临时文件似乎在读取数据之前被删除。

我有关于文件,它的位置的属性,并且当在模拟器中运行时,我甚至确认该文件包含正确的数据,而在断点中。但是,只要调用[NSData dataWithContentsOfFile:[location path]][NSData dataWithContentsOfURL:location],文件就会从文件系统中删除,如果我使用传入NSError的方法,我得到的错误是Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed.

我的代码:

- (void)makeSoapRequest:(NSURL *)url soapRequest:(NSString *)soapRequest completionBlock:(void (^)(NSData *xmlToParse, int error))completionBlock attemptNumber:(int)attemptNumber
{
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:nil delegateQueue:nil];
    NSData *bodyData = [soapRequest dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"" forHTTPHeaderField:@"SOAPAction"];
    [request addValue:[NSString stringWithFormat:@"%d",(int)[bodyData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:bodyData];

    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    if (!(location == nil))
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error)
            {
                NSLog(@"nsurl error was: %@", error);
            }
            else
            {
                NSError* errorObj;
                NSString *path = [location path];

                NSDictionary* attribs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&errorObj];
                NSData *xmlData= [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:&errorObj];
                if (errorObj != nil) {
                    NSLog(@"Attributes of file: %@", attribs);
                    NSLog(@"Error reading the downloaded data, error was: %@", errorObj);
                }
                completionBlock(xmlData, 0);
                return;
            }
        });
    }
    else
    {
        if (error)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(nil,-1);
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(nil,-1);
            });
        }
    }
}];
[downloadTask resume];
}

我的属性打印输出:

Attributes of file: {
NSFileCreationDate = "2016-11-23 13:15:00 +0000";
NSFileExtensionHidden = 0;
NSFileGroupOwnerAccountID = 501;
NSFileGroupOwnerAccountName = mobile;
NSFileModificationDate = "2016-11-23 13:15:00 +0000";
NSFileOwnerAccountID = 501;
NSFileOwnerAccountName = mobile;
NSFilePosixPermissions = 384;
NSFileReferenceCount = 1;
NSFileSize = 947;
NSFileSystemFileNumber = 534146;
NSFileSystemNumber = 16777218;
NSFileType = NSFileTypeRegular;
}

错误日志:

2016-11-23 13:27:43.285 GCMMobile[2780:829109] Error reading the downloaded data, error was: Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x1704605c0 {NSFilePath=/private/var/mobile/Containers/Data/Application/BF6BE574-AA1A-492E-A1DD-04334F33E2D7/tmp/CFNetworkDownload_VHyKp6.tmp, NSUnderlyingError=0x17024ce10 "The operation couldn’t be completed. No such file or directory"}

任何最感谢的帮助...

1 个答案:

答案 0 :(得分:2)

问题是您在移动或打开下载的文件之前从NSURLSessionDownloadTask完成处理程序返回。正如documentation所述:

  

您必须在完成之前移动此文件或将其打开以供阅读   处理程序返回否则,文件将被删除,数据将丢失。

通过调度到主队列并返回,您将文件读取代码推迟到将来的某个无限期。您应该在完成处理程序本身中移动或打开文件,然后才会调度到另一个队列以进行后续处理。