#define kAppleUrlToCheckNetStatus @"http://captive.apple.com/"
- (BOOL)checkNetCanUse {
__block BOOL canUse = NO;
NSString *urlString = kAppleUrlToCheckNetStatus;
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.timeoutIntervalForRequest = 3;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
//**// 使用信号量实现NSURLSession同步请求**
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[[session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString* result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//解析html页面
NSString *htmlString = [self filterHTML:result];
//除掉换行符
NSString *resultString = [htmlString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
if ([resultString isEqualToString:@"SuccessSuccess"]) {
canUse = YES;
NSLog(@"手机所连接的网络是可以访问互联网的: %d",canUse);
}else {
canUse = NO;
NSLog(@"手机无法访问互联网: %d",canUse);
}
dispatch_semaphore_signal(semaphore);
}] resume];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return canUse;
}
- (NSString *)filterHTML:(NSString *)html {
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:html];
while ([theScanner isAtEnd] == NO) {
// find start of tag
[theScanner scanUpToString:@"<" intoString:NULL] ;
// find end of tag
[theScanner scanUpToString:@">" intoString:&text] ;
// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
html = [html stringByReplacingOccurrencesOfString:
[NSString stringWithFormat:@"%@>", text]
withString:@""];
}
return html;
}
iOS同步检测网络是否可用
猜你喜欢
转载自blog.csdn.net/u010462316/article/details/80705944
今日推荐
周排行