I have a UIImageView. The image for this imageView is loading from web. Can someone please tell me how to stop the loading?
This is my code:
UIImageView *currentImgView = (UIImageView *)[self.scrollView viewWithTag:self.pageControl.currentPage + 500];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *newImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[[self.imagesStructure valueForKey:DATA_PARAMETER] objectAtIndex:self.pageControl.currentPage] valueForKey:@"source"]]]];
dispatch_async(dispatch_get_main_queue(), ^{
currentImgView.image = newImg;
[self hideActivityView];
});
});
You cannot do this with
dataWithContentsOfURL:
. You will need to switch to downloading the data withNSURLConnection
rather than adispatch_async
. You can then call[connection cancel]
to stop the download. See the URL Loading System for full details on setting this up.Note that in most cases, it's not worth the trouble to cancel downloads unless the file is quite large. By the time you've gotten around to canceling, the data is often already in flight, and you might as well just throw it away rather than try to cancel (because you're going to get it anyway).
To implement this approach, you would check for cancellation right before your
currentImgView.image = newImg
line. You should generally do this anyway (since it's possible the download was cancelled between the time you downloaded it and the time the main queue ran again). A good way to attack this problem is with anNSOperaration
, since it gives you access to a convenientcancel
method. Note that canceling an operation just sets a flag. It's up to you to check that that flag and stop processing.