Iphone – Where to use UIActivityIndicatorView


I have written my code in -(void)loadView{ } to get an image from internet using NSURL. But before loading image I need to show the spinner( UIActivityIndicatorView ).

#import "ImageFromWebViewController.h"
@implementation ImageFromWebViewController
+(NSString *)fileName 
    return @"http://happyhyderabad.files.wordpress.com/2009/04/anushka4.jpg";
    return @"http://nutritionresearchcenter.org/healthnews/wp-content/uploads/2008/07/johnny_depp.jpg";

- (void)loadView {
    NSString *urlString = [ImageFromWebViewController fileName];
    NSURL *url = [NSURL URLWithString:urlString];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    imageView = [[UIImageView alloc] initWithImage:image];
    contentView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    [contentView setContentSize:[image size]];
    [contentView addSubview:imageView];
    [imageView setUserInteractionEnabled:NO];
    self.view = contentView;

- (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];

- (void)dealloc {
    [imageView release];
    [contentView release];
    [super dealloc];

In viewDidLoad I wrote the code for UIActivityIndicatorView but the spinner started after loading of the image and it is not stopping.

Where should I write the code for the spinner ?

Best Solution

You need to download the image in a background thread first. In viewDidLoad, you need to start your spinner, then kick off your background thread. Hiding the spinner and drawing the image is up to you how you want to do it. You could hide the spinner in your background thread after the download is finished, but strictly speaking it's usually better to not modify the user interface from any thread other than the main thread.

If you don't want to bother with dealing with your own background threads, take a look at [NSURLConnection connectionWithRequest:delegate:]. That will kick off its own background thread to allow you to asynchronously load data. In this case, still start your spinner in viewDidLoad, then deal with the NSURLConnection stuff, and in the delegate callback method that's called when the data is finished being downloaded, hide the spinner (since you'll be back in the main thread at that point, I believe).

Related Question