Question

I have a UITabBar Application with two views that load large amounts of data from the web in their "viewWillAppear" methods. I want to show a progress bar or an activity indicator while this data is being retrieved, to make sure the user knows the app isn't frozen.

I am aware that this has been asked before. I simply need some clarification on what seems to be a rather good solution.

I have implimented the code in the example. The question's original asker later solved their problem, by putting the retrieval of data into another "thread". I understand the concept of threads, but I do not know how I would impliment this.

With research, I have found that I need to move all of my heavy data retrieval into a background thread, as all of the UI updating occurs in the main thread.

If one would be so kind as to provide an example for me, I would be very appreciative. I can provide parts of my existing code as necessary.

Was it helpful?

Solution

If you use NSURLConnection it runs on another thread automatically.

in your viewDidLoad:

NSURLRequest *req = [NSURLRequest requestWithURL:theURL];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];

then you need some custom methods. If you type in -connection and press Esc you'll see all the different methods you can use. There are three you will need with this:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // this is called when there is a response
        // if you're collecting data init your NSMutableData here
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // each time the connection downloads a 
        // packet of data it gets send here
        // so you can do [myData appendData:data];
} 

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
        // the connection has finished so you can 
        // do what you want with the data here
}

That is basically all there is to it. NSURLConnection handles all the multithreading itself and you don't have to worry. Now you can create an activity indicator and display it and it will work because the main thread is empty. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top