从 ASIHTTPRequest 到 AFNetworking

From ASIHTTPRequest to AFNetworking

我正在关注 http://www.raywenderlich.com/4295/multithreading-and-grand-central-dispatch-on-ios-for-beginners-tutorial 中关于多线程的教程。在本教程中使用了 ASIHTTPRequest,我看到 AFNetworking 现在几乎已成为标准。

我正在尝试使用此块下载 zip 文件:

  __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:sourceURL];
    [request setCompletionBlock:^{
        NSLog(@"Zip file downloaded.");
        NSData *data = [request responseData];
        [self processZip:data sourceURL:sourceURL];        
    }];

我将如何在 AFNetworking 中执行此操作?我需要使用这样的东西吗?

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];

在教程中,我需要下载为 NSData,而在 AFNetworking 中,我需要使用 NSURlResponse。

任何关于此的指示都会很棒。谢谢:)

我会认真地去看看 Apple 关于 NSURLSession 的文档。在 NSURLSession 之前,使用 NSURLConnection 配置一个简单的 upload/download 任务有点痛苦(至少可以这么说),因此 AFNetworking 变得非常流行......并且当之无愧。

但是 NSURLSession 已经解决了很多问题,总的来说,了解真正的 API 与第三方是个好主意(并且没有不尊重 AFNetworking 的意思)。

NSURLSession 的学习曲线降低了很多,它并不比学习 AFNetworking 差多少……至少恕我直言。

为了更具体地说明您的上述问题,我相信您只需将上述 AFURLSessionManager 调用替换为等效的 NSURLSessionManager 调用即可。

我想 AFNetworking 部分看起来不错。只需尝试一下,看看它是否有效。为了检索下载文件的 NSData,您可以使用 NSFileManager 中的 contentsAtPath 方法。

示例:

completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
    NSString *path = [filePath path];
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path]; 
}];