Asynchronous HttpRequest
In first, second and third session of HttpRequest we have learnt how to create a synchronous HttpRequest, in this session we will learn how to make a Asynchronous calls. We also learn how to add activity indicator to show the user some network calls are going on in the background.
Spinning wheel (Activity indicator)
Drag and drop Activity Indicator from Object Library from right side bar of Xcode. Add it to the storyboard of the project that we created in the previous session. Then control + drag it to it's class to create a property for it. Now in viewDidLoad before httpGetRequest method start the activity indicator like bellow:[self.activityIndicator startAnimating];Then we can stop it and hide it or remove it from the view like bellow:
[self.activityIndicator stopAnimating]; //Stop animating self.activityIndicator.hidden = YES; //Hide it [self.activityIndicator removeFromSuperview]; //Remove it from view
How to send Asynchronous NSURLRequest
For Asynchronous HttpRequest we don't need RestApi class that we created in last three sessions. instead we use the following method:[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { //Do whatever you want after response received [self getReceivedData:data]; }];getReceivedData:data is a method that we created in last tutorial we changed it a little bit since we didn't need RestApi class so we removed the sender argument and also we changed the type od NSMutableData into NSData. If we want to handle errors we have:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (!connectionError && [data length] > 0) { [self getReceivedData:data]; } else { NSLog(@"%@", connectionError.description); } }];
No comments:
Post a Comment