2013-05-17 87 views
11
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http:///]; 
NSURLRequest *req = [[NSURLRequest alloc]initWithURL:url]; 
NSURLConnection *con = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES]; 

在我的項目中,我在NSURLConnection上使用了sendSynchronousRequest。它有時會讓我崩潰。異步請求示例

因此,我將此代碼轉換爲AsynchronousRequest。我找不到合適的代碼。

有人給我鏈接或郵政編碼適合我的代碼。任何希爾將不勝感激。

+2

您可能會因爲過於開放和本地化而關閉此問題。我建議你描述你正在嘗試做什麼,你嘗試過什麼,以及爲什麼它不起作用,以便人們可以直接回答請求。有很多人願意並且能夠提供幫助,但更具體的問題表明你已經嘗試了什麼,以及爲什麼它不工作,往往是那些能夠得到最好答案的問題。 – gaige

+0

@gaige我愛它沒有被關閉:) – Supertecnoboff

回答

20

有幾件事情你可以做。

  1. 您可以使用sendAsynchronousRequest並處理回調塊。
  2. 您可以使用AFNetworking庫以異步方式處理所有請求。非常容易使用和設置。

代碼選項1:

NSURL *url = [NSURL URLWithString:urlString]; 
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; 
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
    if (error) { 
    //NSLog(@"Error,%@", [error localizedDescription]); 
    } 
    else { 
    //NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]); 
    } 
}]; 

代碼選項2:

您可能需要下載該庫&包括在您的項目第一。然後執行以下操作。您可以按照設置後的帖子here

NSURL *url = [NSURL URLWithString:@"http://httpbin.org/ip"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
    NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"origin"]); 
} failure:nil]; 

[operation start]; 
+1

當網絡緩慢時,它會阻止用戶交互嗎? – Xcode

+0

我用你的1選項。如何處理它不是成功? – Xcode

+0

您可以在completionHandler塊中使用NSError *錯誤來處理任何錯誤。 – Harish