Reputation: 701
When my code hits the web service call, the activity indicator does not show up, and the button freezes in the "selected" state. I would like the activity indicator to run while the web service call is made, so that the screen does not look like it's freezing.
Here is my code to start the activity Indicator:
[activityInd startAnimating];
Here is my code to make a web service call:
NSString *urlString = [NSString stringWithFormat:@"http://us.api.invisiblehand.co.uk/v1/products?query=%@&app_id=dad00cb7&app_key=ab386c3e1b99b58b876f237d77b4211a", [[searchedItem.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"]];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *itemCallArray = [NSArray arrayWithArray:dataDictionary[@"results"]];
How do I make the Activity Indicator and the Web Service call run on two separate threads?
Upvotes: 0
Views: 114
Reputation: 6192
Don't rewrite your code, just run it in the background.
NSString *urlString = [NSString stringWithFormat:@"http://us.api.invisiblehand.co.uk/v1/products?query=%@&app_id=dad00cb7&app_key=ab386c3e1b99b58b876f237d77b4211a", [[searchedItem.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"]];
[activityInd startAnimating];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *itemCallArray = [NSArray arrayWithArray:dataDictionary[@"results"]];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[activityInd stopAnimating];
});
});
Upvotes: 2
Reputation: 69
Are you running web service call on the main thread. You should never run this on the main thread. This would freeze the GUI and the OS will terminate your app.
Run activity indicator on the main thread and run web service call in another by using blocks.
please let me know if you need more details on how to do this.
Upvotes: 0