在我的代码中,我曾经使用三种方法来检查互联网,但它们有限制:
1/可达性方法:
- (BOOL)isInternetOk
{
Reachability *curReach = [Reachability reachabilityWithHostName:@"apple.com"];
NetworkStatus netStatus = [curReach currentReachabilityStatus];
if (netStatus != NotReachable) //if internet connexion ok
{
return YES;
}
else
{
return NO;
}
}
限制:它在大多数情况下都有效,但我的问题是,如果我在没有互联网的情况下连接天线Wi-Fi,它会说连接正常,但事实并非如此。这不是一个好的解决方案,我需要检查状态代码,它似乎在 Reachability 上不可用。
2/发送同步请求:
- (BOOL)isInternetOk2
{
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:@"https://www.google.com"];
NSError *error = nil;
[request setURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:15];
NSData* response2 = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if (error)
{
return NO;
}
else
{
return YES;
}
}
限制:它也有效,但我的问题是,如果超时,这种情况随时都可能发生,它会在太多时间内冻结应用程序。如果我把它放在一个线程中,似乎当我在dispatch_async中发出请求时,不会考虑响应。
3/发送同步请求:
NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://www.google.com"]];
request.timeoutInterval = 10;
[NSURLConnection sendAsynchronousRequest:request queue:myQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"response status code: %ld, error status : %@", (long)[httpResponse statusCode], error.description);
if ((long)[httpResponse statusCode] >= 200 && (long)[httpResponse statusCode]< 400)
{
// do stuff
NSLog(@"Connected!");
}
else
{
NSLog(@"Not connected!");
}
}];
限制:我认为这是更好的方法,但我的问题是我必须在代码中的每个地方编写它,这将是一种污染。我想知道是否有一种不太重的方法可以做到这一点。
你怎么看待这件事?有没有另一种方法可以更轻松地检查互联网是否正常工作而无需冻结应用程序?
提前致谢。