0

我正在使用AFHTTPRequestOperation将一个大文件下载到我设备上的 Documents 目录中。

NSURLRequest *request = [NSURLRequest requestWithURL:vectorFile.url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

NSString *path = [self pathForFileName:vectorFile.fileName];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    double percentDone = (double)totalBytesRead / (double)totalBytesExpectedToRead;
    progress(percentDone, totalBytesRead, totalBytesExpectedToRead);

}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        NSString *path = [self pathForFileName:vectorFile.fileName];

        extracting();
        [SSZipArchive unzipFileAtPath:path toDestination:[self path] progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {

            NSLog(@"Unzipping");

        } completionHandler:^(NSString *path2, BOOL succeeded, NSError *error) {

            if (!error) {
                NSLog(@"Successfully downloaded file to %@", path);


                dispatch_async(dispatch_get_main_queue(), ^{

                    completion(YES);

                });
            } else {

                NSLog(@"%@", error);
                failure(error);

            }


        }];

    });


} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {

    NSLog(@"%@", error);
    failure(error);

}];
[operation start];

出于某种奇怪的原因,它可以在模拟器上下载文件,但在设备(iPhone 6)上我收到以下错误:

Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"

URL 是正确的,因为它在我的浏览器和模拟器中正确下载。为什么这只会发生在设备上?什么可能导致它?

我已尝试重新启动设备并重置网络设置。

4

2 回答 2

3

如果您使用,也可能会引发此错误(没有此类文件或目录)[NSURLSessionConfiguration backgroundConfiguration]

至少在 iOS 10 中,如果您尝试使用任何 resumeData 恢复此类任务,您的会话委托调用将返回该错误。

不确定自 iOS 9 以来发生了什么变化,因为这在 iOS 7-9 中可以正常工作。

于 2017-07-04T16:38:30.277 回答
1

在这里发表评论后,我发现我需要先检查我的目标目录是否已创建:

if(![[NSFileManager defaultManager] fileExistsAtPath:[self path]]) {
     [[NSFileManager defaultManager] createDirectoryAtPath:[self path] withIntermediateDirectories:YES attributes:nil error:NULL];
}

我原以为outputStream会为我创造它。甚至奇怪的是它在模拟器中正常工作。

于 2016-07-27T23:52:05.793 回答