我正在使用更新的Reachability库来测试互联网连接是否可以访问。我尝试记录一条消息,以防无法访问互联网,但日志不会调试:
//Test the internet connection
Reachability* reach = [Reachability reachabilityForInternetConnection];
reach.unreachableBlock = ^(Reachability*reach)
{
NSLog(@"Internet connexion unreachable");//Although Internet cnx is off, this message is not displayed
return;
};
// start the notifier which will cause the reachability object to retain itself!
[reach startNotifier];
我是否误解了Reachability库?互联网关闭时如何执行给定任务?感谢名单。
P.S:我的iPad只有wifi,没有3G服务。答案 0 :(得分:2)
使用Alamofire检查interner,在Swift 4中
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
然后调用此函数
if Connectivity.isConnectedToInternet() {
print("Yes! internet is available.")
// do some tasks..
}
答案 1 :(得分:0)
实际上,您应该注册接收更改可达性的通知:
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
答案 2 :(得分:0)
好的,我得到的最好方法是关注Apple示例代码:
//Test the internet connection
Reachability* reach = [Reachability reachabilityForInternetConnection];
NetworkStatus netStatus = [reach currentReachabilityStatus];
//See if the reachable object status is "ReachableViaWifi"
if (netStatus!=ReachableViaWiFi) {
//If not
NSLog(@"wifi unavailable");
//Alert the user about the Internet cnx
WBErrorNoticeView *notice = [WBErrorNoticeView errorNoticeInView:self.view title:@"Network Error" message:@"Check your internet connection."];
notice.sticky = NO;
[notice show];
return;//Exit the method
}