AFNetworking 1.x到3.x迁移 - 获取下载进度?

时间:2016-02-12 08:56:31

标签: objective-c ios9 nsurlsession nsurlsessiondownloadtask afnetworking-3

我需要使用进度条下载图像。这就是我在AFNetworking 1.x中所获得的,它不适用于AFNetworking 3.x.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.mediaItem.media_item_hd_url]];

AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFImageResponseSerializer serializer];

[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    UIImage *image = responseObject;
    _image = image;

    [self.delegate browserItem:self loaded:1.0 finished:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { }];

[op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    CGFloat progress = ((CGFloat)totalBytesRead)/((CGFloat)totalBytesExpectedToRead);
    [self.delegate browserItem:self loaded:progress finished:NO];
}];

[[NSOperationQueue mainQueue] addOperation:op];

最后,这是我能想到的,这是不完整的。我不知道如何在代码块中使用进度。

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.mediaItem.media_item_hd_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);
//        UIImage *image = response;
//        _image = image;

        [self.delegate browserItem:self loaded:1.0 finished:YES];

    }];

    [downloadTask resume];

1 个答案:

答案 0 :(得分:0)

您可以轻松获得最佳框架 RSNetworkKit ,它可以轻松处理所有网络呼叫。它内部实现了 AFNetworking 3.0。它可以为您提供上传,下载的单一方法的下载进度。

它还有一个增强的方法来显示 UIImageView 的进度。 你可以在这里找到它。 https://github.com/rushisangani/RSNetworkKit