尝试为我的 iPhone 程序编写一个方法,为文件提供 URL 地址,它将下载到 iOS 应用程序的文档目录。
按照 AFNetowrking 的文档,它似乎工作正常,只是文件名总是一些垃圾。
我正在使用 Xcode 5,并将 AFNetworking 2.0 添加到我的项目中。这是我到目前为止的代码:
//#import "AFURLSessionManager.h"
//On load (or wherever):
[self downloadFile:@"http://www.irs.gov/pub/irs-pdf/fw4.pdf"];
-(void)downloadFile:(NSString *)UrlAddress
{ NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:UrlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
{
NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];
}
completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
{
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
}
最终结果是文件成功下载到我的文档目录中,但是名称是乱码:
文件下载到:file:///Users/myname/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/25188DCA-4277-488E-B08A-4BEC83E59194/Documents/CFNetworkDownload_60NWIf.tmp
我期待的最终结果:
文件下载到:file:///Users/myname/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/25188DCA-4277-488E-B08A-4BEC83E59194/Documents/fw4.pdf
我使用 cocoapods 将 AFNetworking 添加到我的项目中: pod 'AFNetworking', "~> 2.0"
最后,我需要做什么才能获得下载进度?