2013-01-23 21 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並返回響應? –