I am using following code to get results from server
NSString *queryString = @"MyString"
NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:queryString] encoding:NSUTF8StringEncoding error:&err];
NSLog(@"%@",response);
if (err != nil)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Error"
message: @"An error has occurred. Kindly check your internet connection"
delegate: self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
[indicator stopAnimating];
}
else
{
//BLABLA
}
The problem with this code is ,If server shows lag and it takes lets say 3 seconds to get this response
NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:queryString]
For 3 seconds my iPhone screen is jammed. How can i make it run in background so that it won’t slow down or jam the mobile
Regards
What you are doing is sending HTTP request from the main thread. that will jam up the UI as you said. You need to spawn a background thread and make a request to your server, when the response comes back then you need to update the UI from the main thread. This is a common pattern in UI coding.
You can also use
performSelectorInBackground:withObject:to spawn a new thread, then the performed selector is responsible for setting up the new thread’s autorelease pool, run loop and other configuration details – see “Using NSObject to Spawn a Thread” in Apple’s Threading Programming Guide.You’d probably be better off using Grand Central Dispatch as I posted above. GCD is a newer technology, and is more efficient in terms of memory overhead and lines of code.