我目前正在使用完成块能够使用以下代码检查是否存在到服务器的连接,但是您可以肯定地告诉它挂起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