Quantcast
Viewing all articles
Browse latest Browse all 3667

How to handle asynchronous requests to rest APIs in an iOS app

Let's say I want to use the rest API of some service, Twitbookr, to get a user's profile information. So I get the user to log in via my app and I get the credentials needed to make the call.

After this I load a new ViewController. I want to populate the fields in this view with the user's profile information. So I make my first call to the API:

[NSURLConnection sendAsynchronousRequest:req                  queue:NSOperation.mainQueue                  completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){    // successfully fetch data using credentials    // assume complete code here including dispatch_async etc    self.data = data;})];

Then I want to use the data:

self.nameLabel.text = [self.data objectForKey:@"name"];self.userid = [self.data objectForKey:@"userid"];

But the request hasn't finished yet, so the program throws an error.

And I want to make more calls to get different types of data, for example, the pictures from the frontpage album, which rely on the userid which I can only get from the request above. So how do I make my next subsequent call making sure I already have the userid from the first call?

What's the correct way to handle this situation?

Should I be using synchronous requests instead?Should I put up a loading symbol until all of my requests are done? If so, how do I test that the requests have actually finished? And what's the point of them being asynchronous?


Viewing all articles
Browse latest Browse all 3667

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>