AFNetworking setImageWithURLRequest下载进度

时间:2012-12-11 13:25:55

标签: iphone ios ipad afnetworking progress

我正在使用此代码将图像设置为UIImageView。

NSURLRequest *URLRequest = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:imageToLoad]];

    [imageView setImageWithURLRequest:URLRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        [cell.image setImage:image];
        [cell.activityIndicator stopAnimating];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        // Nothing
    }];

但我想用该方法跟踪下载进度,是否可以在setImageWithURLRequest方法中执行此操作?

通常我这样做是为了显示加载进度百分比:

[SVProgressHUD showWithStatus:@"Start download..."];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:link]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        // success
        [SVProgressHUD showSuccessWithStatus:@"Done."];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // failed
        [SVProgressHUD showErrorWithStatus:@"Failed."];
    }];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"Downloading... %0.0f%%", totalBytesRead*100*1.0/(totalBytesRead+totalBytesExpectedToRead)]];
    }];

2 个答案:

答案 0 :(得分:2)

开箱即用,没有UIImageView + AFNetworking类别没有此功能。但是,可以通过将此方法添加到类别中来轻松添加它:

-(void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead,   long long totalBytesExpectedToRead))block{
   [self.af_imageRequestOperation setDownloadProgressBlock:block];
}

答案 1 :(得分:1)

看看这个可可豆荚:https://github.com/xmartlabs/XLRemoteImageView。它使用objective-c内部来实现你想要的。我希望它可以帮助你。