问题
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
回答1:
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.
__block__ NSString *response;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//your server url and request. data comes back in this background thread
response; = [NSString stringWithContentsOfURL:[NSURL URLWithString:queryString] encoding:NSUTF8StringEncoding error:&err];
dispatch_async(dispatch_get_main_queue(), ^{
//update main thread here.
NSLog(@"%@",response);
if (err != nil)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Error"
message: @"An error has occurred."
delegate: self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
[indicator stopAnimating];
}
});
});
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.
回答2:
You could use ASIHTTPRequest which is my favorite for getting and sending information.
来源:https://stackoverflow.com/questions/14475129/speed-up-the-response-retriever-from-server-in-iphone