Ios 如何使用AFNetworking 3.0下载文件并保存到本地?
在我的项目中,我需要下载一个小视频。在以前的版本中,我使用以下方法:Ios 如何使用AFNetworking 3.0下载文件并保存到本地?,ios,objective-c,Ios,Objective C,在我的项目中,我需要下载一个小视频。在以前的版本中,我使用以下方法: - (void)downloadFileURL:(NSString *)aUrl savePath:(NSString *)aSavePath fileName:(NSString *)aFileName tag:(NSInteger)aTag; 在AFNetworking 3.0中如何执行此操作?此代码: NSURLSessionConfiguration *configuration = [NSURLSessionCon
- (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];
在该项目的自述文件中:我意识到最初的问题是在Obj-C中,但这是在谷歌搜索中出现的,因此对于任何其他绊倒它并需要@Lou Franco答案的快速版本的人,这里是:
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
- 我还添加了一个
closure(只是一个progress
语句)。但是当然,在那里传递print
是完全可以的,就像在原始示例中一样nil
- 有三个地方(标有
)没有错误处理,可能出现故障。显然,您应该处理这些错误,而不仅仅是崩溃TODO: