一、说明
监测网络状态的意义:
1.通过对网络状态的监控,可以让应用在联网与不联网这两种状态中,做出相应的响应
2.及提醒用户,现在是处在什么网络状态下。
二、方法
苹果官方提供了一个叫Reachability的示例程序
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
1.添加框架SystemConfiguration.framework
Xcode -> “项目” -> Build Phases -> Link Binary With Libraries -> + ![图片描述][1]
Reachability.h Reachability.m ![图片描述][2]
3.在桥接头文件中引入
#import "Reachability.h"
4.代码示例
override func viewDidLoad() { //添加通知,当收到通知时,调用inspectNetworkState()方法 let center = NSNotificationCenter.defaultCenter() center.addObserver(self,selector: Selector(inspectNetworkState()),name: kReachabilityChangedNotification,object: nil) } func inspectNetworkState() { //监测wifi状态 let wifi = Reachability.reachabilityForLoaclWifi() //监测手机是否能连移动网络(2g/3g) let mobile = Reachability.reachabilityForInternetConnection() //判断网络的状态 if (wifi.currentReachabilityStatus() != NotReachable) { print("当前是wifi网络") } else if (mobile.currentReachabilityStatus() != NotReachable) { print("当前是移动3g/4g网络") } else { print("当前无网络") } }原文链接:https://www.f2er.com/swift/324005.html