在移动开发过程中,对于网络状态的监测尤为重要
直接上代码
/**
通过消息自动监听网络改变
添加消息监听
*/
func autoNetworkStatus() {
// 1、设置网络状态消息监听
NSNotificationCenter.defaultCenter().addObserver(self, selector: "networkStatusChange", name: kReachabilityChangedNotification, object: nil);
// 2、获得网络Reachability对象
// Reachability必须一直存在,所以需要设置为全局变量
conn = Reachability.reachabilityForInternetConnection();
// 3、开启网络状态消息监听
conn.startNotifier();
}
func networkStatusChange() {
checkNetworkStatus();
}
/**
移除消息通知
*/
deinit {
// 关闭网络状态消息监听
conn.stopNotifier();
// 移除网络状态消息通知
NSNotificationCenter.defaultCenter().removeObserver(self);