0

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

回答

1

很多方法可以做到这一点,但你已经在使用sendSynchronousRequest为什么不只是使用sendAsynchronousRequest

[NSURLConnection sendAsynchronousRequest:request 
            queue:[NSOperationQueue mainQueue] 
         completionHandler: 
^(NSURLResponse *response, NSData *data, NSError *connectionError) 
{ 
    block([(NSHTTPURLResponse *)response statusCode] == 200); 
} 
]; 
+1

有时候我们会让事情变得复杂 – klcjr89

0

与尝试:

- (void)checkInternet:(connection)block 
{ 
    dispatch_async(dispatch_get_global_queue(0,0), ^{ 
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]]; 
     [request setHTTPMethod:@"HEAD"]; 
     NSHTTPURLResponse *response; 
     [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL]; 
     block(([response statusCode] == 200) ? YES : NO); 
    }); 
} 
+0

我只是试过了,它没有返回正确的值 – klcjr89

+0

@ troop231:你确定吗?因为整个代码在dispatch_async下,所以可能它应该起作用。从方法体中删除gcd,并检查在调用方法时会发生什么情况:dispatch_async(dispatch_get_global_queue(0,0),^ {[self checkInternet:^(BOOL internet) 如果(互联网) { NSLog(@ “Internet”); } else { NSLog(@“No internet”); } }];}); –

+0

哦,代码工作正常,没有GCD包装,这使得它的异步问题没有得到正确的布尔之外 – klcjr89