开发过程中,需要监听网络的连接状态,那么如何去监听呢?
一、监听——网络连接状态变化自动调用回调
Swift版本
-
通过CocoaPods或者Carthage安装Reachability,地址:https://github.com/ashleymills/Reachability.swift
-
通过闭包测试reachability
let reachability = Reachability()! reachability.whenReachable = { reachability in if reachability.connection == .wifi { print("Reachable via WiFi") } else { print("Reachable via Cellular") } } reachability.whenUnreachable = { _ in print("Not reachable") } do { try reachability.startNotifier() } catch { print("Unable to start notifier") }
Objective-C版本
-
添加
SystemConfiguration
framework到项目中 -
添加Tony Million’s 版本的
Reachability.h
和Reachability.m
到项目中,地址:https://github.com/tonymillion/Reachability -
更新接口部分
#import "Reachability.h" @interface MyViewController () { Reachability *_internetReachableFoo; } @end
-
.m文件中执行对应的方法
// 检查我们是否有互联网连接 - (void)testInternetConnection { _internetReachableFoo = [Reachability reachabilityWithHostname:@"www.baidu.com"]; // 网络可用 _internetReachableFoo.reachableBlock = ^(Reachability*reach) { //主线程更新UI dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"网络可用"); }); }; // 网络不可用 _internetReachableFoo.unreachableBlock = ^(Reachability*reach) { //主线程更新UI dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"网络不可用"); }); }; [_internetReachableFoo startNotifier]; }
重要提示:
Reachability
类是项目中最常用的类之一,因此您可能会遇到与其他项目的命名冲突。如果发生这种情况,您将不得不重命名Reachability.h
和Reachability.m
为其他名称以便解决问题。
二、主动获取——使用网络时调用方法判断
1.使用Reachability版本
-
添加
SystemConfiguration
framework到项目中 -
添加Tony Million’s 版本的
Reachability.h
和Reachability.m
到项目中,地址:https://github.com/tonymillion/Reachability -
函数
//Class.h
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>
- (BOOL)connected;
//Class.m
- (BOOL)connected
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return networkStatus != NotReachable;
}
在需要判断网络连接状态的地方调用方法如下:
if (![self connected]) {
// Not connected
} else {
// Connected. Do some Internet stuff
}
2.非Reachability版本
- 添加
SystemConfiguration
framework到项目中 - 导入头文件
#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>
- 调用方法
+(BOOL)hasConnectivity {
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
if (reachability != NULL) {
//NetworkStatus retVal = NotReachable;
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
{
// If target host is not reachable
return NO;
}
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
// If target host is reachable and no connection is required
// then we'll assume (for now) that your on Wi-Fi
return YES;
}
if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
// ... and the connection is on-demand (or on-traffic) if the
// calling application is using the CFSocketStream or higher APIs.
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
// ... and no [user] intervention is needed
return YES;
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
return YES;
}
}
}
return NO;
}
demo
https://github.com/zhzhl1993/MacOS-Development/tree/master/Demo/TestReachbility
参考文献
How to check for an active Internet connection on iOS or macOS?