【问题标题】:AFNetworking downloadTaskWithRequest:progress:destination:completionHandler: not writing file to the pathAFNetworking downloadTaskWithRequest:progress:destination:completionHandler: 不将文件写入路径
【发布时间】:2015-06-16 10:44:40
【问题描述】:

我正在尝试使用 AFNetworking (2.5.4) 下载文件。下载完成,调用完成处理程序,错误设置为 nil,一切正常,但目标文件不存在:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSString *fullPath = [valid path from my apps local manager]
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:req progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    return [NSURL URLWithString:fullPath];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"Saved file to %@.", filePath);
    *** [[NSFileManager defaultManager] fileExistsAtPath:filePath.absoluteString] returns NO here ***
}];
[cell.progressView setProgressWithDownloadProgressOfTask:downloadTask animated:YES];
[downloadTask resume];

文件路径是我的应用具有写入权限的常规路径:

/var/mobile/Containers/Data/Application/APP-GUID-REDACTED/Documents/FILE-NAME-REDACTED.docx

我在 AFNetworking 之前使用了不同的方法,它可以写入完全相同的路径。 HTTP 响应标头完美地显示了所有内容(状态 200、正确的内容长度等),如果我 curl 下载 URL,它会毫无问题地下载文件。文件没有问题。

为什么我的目标文件没有写入完成处理程序,尽管没有错误?

更新:我也尝试过AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];,但它没有任何改变。我还尝试创建一个 NSProgress 指针并将其发送给 progress 参数,但无济于事。

【问题讨论】:

    标签: ios ios8 afnetworking-2


    【解决方案1】:

    使用 [NSURL fileURLWithPath:](不是 URLWithString)。

    return [NSURL fileURLWithPath:fullPath];
    

    【讨论】:

      【解决方案2】:

      这里的问题是错误的文件路径或无效的文件路径。我在这里遇到了同样的问题。

      如下所示创建路径:

      NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
      NSURL *filePathURL = [documentsDirectoryURL URLByAppendingPathComponent:[NSString stringWithFormat:@"your file name here",i]];
      

      现在使用上面的路径:

      NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:req progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
          return filePathURL;
      }
      

      【讨论】:

      • 复制粘贴,没有任何改变。您的代码生成的路径与我的完全相同,但它再次为零。
      猜你喜欢
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 2021-02-16
      相关资源
      最近更新 更多