2010-11-27 71 views

回答

2

如果你還沒有下載大量並行的東西,你正在做一個簡單的GET請求,要做到這一點是派遣一個同步請求的最簡單方法全球隊列:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]]; 
    NSURLResponse* response = nil; 
    NSError* error = nil; 
    NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    // There will be response data in response now, like the http status code 
    // etc. You should check this information to make sure you didn't get a 404 
    // or some other http status error 
    if(result) { 
    // you have a good result, do something with it like create a new object or 
    // pass it to a method on this object, etc. 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self doSomethingWithResponseData:result]; 
    }); 
    } else { 
    // You got an error making the connection, so handle it 
    NSLog(@"Error making connection: %@", error); 
    } 
}); 

**注意:此示例代碼使用GCD,因此只能在Snow Leopard(10.6)或更高版本上運行。如果您需要定位Leopard或Tiger,則可以使用調度的線程選擇器執行相同的操作,但不能使用線內選擇器。

相關問題