Search code examples
iphoneiosipadafnetworkingprogress

AFNetworking setImageWithURLRequest download progress


I am using this code to set image to 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
    }];

But I want to track download progress with that method, is it possbile to do it in setImageWithURLRequest method?

Normally I do this to show loading progress percentage:

[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)]];
    }];

Solution

  • Out of the box, no UIImageView+AFNetworking category doesn't have this functionality. However, it can easily be added to by adding this method to the category:

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