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

Kin*_*tar 9 objective-c ios

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

- (void)downloadFileURL:(NSString *)aUrl savePath:(NSString *)aSavePath fileName:(NSString *)aFileName tag:(NSInteger)aTag;
Run Code Online (Sandbox Code Playgroud)

我怎么能在AFNetworking 3.0中做到这一点?

Lou*_*nco 15

这段代码:

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];
Run Code Online (Sandbox Code Playgroud)

在项目的README上:https://github.com/AFNetworking/AFNetworking


Nik*_*iev 5

我意识到最初的问题出现在Obj-C中,但这出现在谷歌搜索中,所以对于其他任何绊倒它并且需要Swift版本的@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()
Run Code Online (Sandbox Code Playgroud)

几个笔记在这里:

  • 这是Swift 3/Swift 4
  • 我也添加了一个progress闭包(只是一个print声明).但是当然nil在原始例子中传递它完全没问题.
  • 有三个地方(标有TODO:)没有错误处理,事情可能会失败.显然你应该处理这些错误,而不仅仅是崩溃.