这是我的代码:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSString *URLForSend = [NSString stringWithFormat:@"%@/pk/%ld/", [_downloadFileURLString stringByAppendingString:_userName], (long)pk ];
NSURL *URL = [NSURL URLWithString:URLForSend];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
__unsafe_unretained typeof(self) weakSelf = self;
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *downloadDirectoryPath = [self downloadAreaDirectoryURL];
return [downloadDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSString *relativeFilePathString = [filePath lastPathComponent];
[weakSelf updateFilePathFromStack:relativeFilePathString withpk:pk];
NSLog(@"File downloaded to: %@", filePath);
}];
return downloadTask;
我阅读了文档几次,留下了两个问题:
- 在
destination
block 中,它从哪里获取targetPath
? - 在完成处理程序中,
filePath
将我引导至临时文件,我想要最终保存的文件的名称。
我希望将其保存到 downloadedAreaDirectoryURL
(我在缓存文件夹中打开的目录)并使其成为 downloadedAreaDirectoryURL
/fileNameLikeItsCalledFromServer
请注意,在实际获取该文件名之前,我并不知道该文件名,因为我使用数据库中的 PK 编号来访问它
最佳答案
AFURLSessionManager
使用 iOS 7.0 中引入的新NSURLSession
类。具体来说,它使用NSURLSessionDownloadDelegate
和方法 URLSession:downloadTask:didFinishDownloadingToURL: ,它将向临时文件发送一个文件 URL。我刚刚尝试了您发布的相同代码(稍加修改以使路径正确),并且我从
destination
block 到得到了相同的返回 URL
参数。此外,该文件已成功移动到我的缓存目录。我建议您为completionHandler
的 filePathAFURLSessionDownloadTaskDidFailToMoveFileNotification
添加一个监听器,以验证文件移动操作没有失败。
关于ios - AFNetworking 2.0 返回下载临时位置而不是它保存的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20543575/