user2563044
user2563044

Reputation:

iOS: Wait for asynchronous method before populating a tableview

I'm getting some data from my server that I need to use as metadata for creating a table view. The problem is the data loads asynchronously with the flow of the app. I'm sure this is probably a simple fix, but how can I either pause the flow of the app until the data has loaded from the server, or update the table view as the data becomes available?

Thanks!

Upvotes: 2

Views: 1402

Answers (3)

user2071152
user2071152

Reputation: 1195

You can use an UIActivityIndicatorView to show the data is being downloaded. Once the data is downloaded in async mode you can reload UITableView.

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] 
                                       initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    spinner.center = CGPointMake(100, 100);
    spinner.hidesWhenStopped = YES;
    [self.view addSubview:spinner];
    [spinner startAnimating];

Now call your method that downloads data from the network.

[self asyncDownloadMethod];

When you are notified i.e., by any delegate that the contents are downloaded, stop the indicator.

[spinner stopAnimating];

Hope this helps.

Upvotes: 4

Madbreaks
Madbreaks

Reputation: 19539

You haven't provided enough information to answer definitively, but the gist of it is you need to set up a delegate that will handle populating the table view once you've finished loading your data.

For example, the NSURLConnection class defines the connectionWithRequest:delegate: selector for loading data asynchronously. The delegate argument is defined as:

delegate The delegate object for the connection. The connection calls methods on this delegate as the load progresses. Delegate methods are called on the same thread that called this method. For the connection to work correctly, the calling thread’s run loop must be operating in the default run loop mode.

Upvotes: 0

matt
matt

Reputation: 534966

First, make sure that your data source methods are written correctly so that if there is no data yet, the table will indeed be empty. This is because the data source methods will be called when the table first appears, which is before you have data.

Then, when there is data, just call reloadData (on the main thread!). The same data source methods will run again, but this time there is data.

Upvotes: 1

Related Questions