I'm using the AFNetworking library to set images with the contents of URLs. In the following example topLeftImage is an instance of a UIImageView.
[topLeftImage setImageWithURL:[NSURL URLWithString:imageURL]];
What I'd like to do is to show a UIActivityIndicatorView while the image is downloading. However I can't figure where to trigger the starting and stopping of the activity indicator. The following is my code for the activity indicator.
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[topLeftImage addSubview:activityIndicator];
[activityIndicator startAnimating];
How can I link the above code to the setImageWithURL method so that activity indicator appears only while the image is downloading?
UIImageView+AFNetworking.h category provides a setImageWithURL method that allows you to use success and failure blocks. This blocks will be executed once the request finishes in success or fail. So you can start the animation just before the request and put the stop in success and fail blocks. This is a sample code:
NSURL *imageURL = [NSURL URLWithString:@"http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/402px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg"];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageURL];
[_activityIndicator setHidden:NO];
[_activityIndicator startAnimating];
[_imageView setImageWithURLRequest:imageRequest
placeholderImage:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
{
[_activityIndicator setHidden:YES];
[_activityIndicator stopAnimating];
_imageView.image = image;
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
{
[_activityIndicator setHidden:YES];
[_activityIndicator stopAnimating];
}];
Simple extension
for UIImageView
in Swift:
extension UIImageView {
func setImageWithString(string: String?) {
if let string = string, let url = NSURL(string: string) {
let activityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame)))
activityIndicatorView.hidden = false
activityIndicatorView.color = UIColor.lightGrayColor()
addSubview(activityIndicatorView)
bringSubviewToFront(activityIndicatorView)
activityIndicatorView.startAnimating()
setImageWithURLRequest(NSURLRequest(URL: url), placeholderImage: nil, success: { request, response, image in
self.image = image
activityIndicatorView.hidden = true
activityIndicatorView.stopAnimating()
activityIndicatorView.removeFromSuperview()
}, failure: { request, response, error in
activityIndicatorView.hidden = true
activityIndicatorView.stopAnimating()
activityIndicatorView.removeFromSuperview()
})
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With