我目前正在使用完成塊能夠使用以下代碼檢查是否存在到服務器的連接,但是您可以肯定地告訴它掛起UI,因爲它是同步的。但是,通過嘗試使用dispatch_async來封裝它,您無法從異步塊內部獲得正確的返回布爾值(省略了調度代碼)。如何在完成塊內部異步執行同步請求
任何關於如何解決這個問題的指針?
代碼:
typedef void(^connection)(BOOL);
- (void)checkInternet:(connection)block
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:@"http://www.google.com/"]];
[request setHTTPMethod:@"HEAD"];
//[request setTimeoutInterval:3.0];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:NULL];
block(([response statusCode] == 200) ? YES : NO);
}
- (void)theMethod
{
[self checkInternet:^(BOOL internet)
{
if (internet)
{
NSLog(@"Internet");
}
else
{
NSLog(@"No internet");
}
}];
}
有時候我們會讓事情變得複雜 – klcjr89