这是我的代码:
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
块中,它从哪里获得targetPath
- 在完成处理程序中,
filePath
将引导我进入临时文件,我想要最终保存的文件的名称
我希望它被保存到downloadedAreaDirectoryURL
(我在缓存文件夹中打开的目录),并成为downloadedAreaDirectoryURL
/fileNameLikeItsCalledFromServer
请注意,在我真正得到它之前,我不知道这个文件名,因为我使用DB 的PK号访问它
-
AFURLSessionManager
使用iOS 7.0中引入的新NSURLSession
类。具体来说,它使用带有URLSession:downloadTask:didFinishDownloadingToURL:方法的NSURLSessionDownloadDelegate
,该方法将文件URL发送到临时文件。 -
我刚刚尝试了您发布的相同代码(稍作修改以获得正确的路径),并且从
destination
块到completionHandler
的filePath
参数得到了相同的返回URL。此外,该文件已成功移动到我的缓存目录中。我建议您为AFURLSessionDownloadTaskDidFailToMoveFileNotification
添加一个侦听器,以验证文件移动操作没有失败。