在iphone中加速从服务器的响应检索器

我正在使用以下代码从服务器获取结果

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 } 

这个代码的问题是,如果服务器显示滞后,需要3秒钟才能得到这个响应

 NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:queryString] 

3秒钟我的iPhone屏幕卡住了。 我如何使它在后台运行,以便它不会放慢速度或堵塞手机

问候

你正在做的是从主线程发送HTTP请求。 如你所说,这将堵塞用户界面。 你需要产生一个后台线程,并向你的服务器发出请求,当响应返回时,你需要从主线程更新UI。 这是UI编码中的一种常见模式。

 __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]; } }); }); 

你也可以使用performSelectorInBackground:withObject:来产生一个新的线程,然后执行的select器负责设置新线程的自动释放池,运行循环和其他configuration细节 – 请参阅Apple的线程编程指南中的 “使用NSObject生成线程” 。

如上所述,您可能会更好地使用Grand Central Dispatch 。 GCD是一种较新的技术,在内存开销和代码行方面效率更高。

你可以使用ASIHTTPRequest这是我最喜欢的获取和发送信息。