如何使用AFNetworking 3.0下载文件并保存到本地?

在我的项目中,我需要下载一个小video。 在以前的版本中,我使用这个:

- (void)downloadFileURL:(NSString *)aUrl savePath:(NSString *)aSavePath fileName:(NSString *)aFileName tag:(NSInteger)aTag; 

我如何在AFNetworking 3.0中做到这一点?

此代码:

 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { NSLog(@"File downloaded to: %@", filePath); }]; [downloadTask resume]; 

在项目的README文件中: https : //github.com/AFNetworking/AFNetworking

我意识到最初的问题是在Obj-C中,但是这是在Googlesearch中出现的,所以对于其他任何人来说,需要@Lou Franco的答案的Swift版本,这里是:

 let configuration = URLSessionConfiguration.default let manager = AFURLSessionManager(sessionConfiguration: configuration) let url = URL(string: "http://example.com/download.zip")! // TODO: Don't just force unwrap, handle nil case let request = URLRequest(url: url) let downloadTask = manager.downloadTask( with: request, progress: { (progress: Progress) in print("Downloading... progress: \(String(describing: progress))") }, destination: { (targetPath: URL, response: URLResponse) -> URL in // TODO: Don't just force try, add a `catch` block let documentsDirectoryURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) return documentsDirectoryURL.appendingPathComponent(response.suggestedFilename!) // TODO: Don't just force unwrap, handle nil case }, completionHandler: { (response: URLResponse, filePath: URL?, error: Error?) in print("File downloaded to \(String(describing: filePath))") } ) downloadTask.resume() 

几个笔记在这里:

  • 这是Swift 3 / Swift 4
  • 我也添加了一个progressclosures(只是一个print语句)。 但是,在原来的例子中,当然这是完全没有问题的。
  • 有三个地方(标有TODO: ,没有error handling,可能会失败。 显然你应该处理这些错误,而不是只是崩溃。