0

我需要下载带有进度条的图像。这就是我在 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];
4

1 回答 1

0

您可以获得最好的框架RSNetworkKit,它可以轻松处理所有网络调用。它在内部实现了 AFNetworking 3.0。 无论您上传、下载,它都会以单一方法为您提供下载进度。

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

于 2016-02-12T11:07:12.493 回答