2013-01-23 24 views
0

我使用下面的代码从服务器获取结果加快从服务器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屏幕卡住了。我怎样才能使它在后台运行,所以它不会减慢或堵塞移动

问候

回答

1

你正在做什么是发送从主线程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:来生成一个新的线程,然后进行选择是负责建立新线程的自动释放池,跑环和其他配置细节 - 见"Using NSObject to Spawn a Thread"苹果线程编程指南英寸

你可能会更好使用Grand Central Dispatch,因为我在上面发布。 GCD是一种较新的技术,在内存开销和代码行方面效率更高。

+0

你能举一个如何使用我的代码使用我们的代码的例子吗?这将是非常好的你,因为我仍然在我的学习过程:) –

+0

酷!完成后,请检查我的更新答案。 –

+0

我想知道如果我把它转让给我们说NSObject类,并从我的UIViewController调用它,但是当我这样做,它不起作用。我想这样做是因为我必须使用它很多地方,大型代码,所以我只是通过URL并返回响应? –