swift3 xcode 8.3.3
我做了一个按钮来检查可达性,但是如何在应用程序每秒运行期间检查可达性。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func checkAction(_ sender: Any) {
checkReachability()
}
func checkReachability(){
if currentReachabilityStatus == .reachableViaWiFi {
print("User is connected to the internet via wifi.")
}else if currentReachabilityStatus == .reachableViaWWAN{
print("User is connected to the internet via WWAN.")
} else {
print("There is no internet connection")
}
}
}
答案 0 :(得分:1)
您不需要每秒都观察到可达性,因为当互联网可达性发生任何变化时,会有一个委托方法被调用。
func reachabilityChanged(notification: Notification) {
let reachability = notification.object as! Reachability
switch reachability.currentReachabilityStatus {
case .notReachable:
debugPrint(“Network became unreachable”)
case .reachableViaWiFi:
debugPrint(“Network reachable through WiFi”)
case .reachableViaWWAN:
debugPrint(“Network reachable through Cellular Data”)
}
}
但是您需要通过将方法调用startMonitoring()
添加到viewDidLoad()
方法
/// Starts monitoring the network availability status
func startMonitoring() {
NotificationCenter.default.addObserver(self,
selector: #selector(self.reachabilityChanged),
name: ReachabilityChangedNotification,
object: reachability)
do{
try reachability.startNotifier()
} catch {
debugPrint(“Could not start reachability notifier”)
}
}
最后加入
ReachabilityManager.shared.startMonitoring()
这样ReachabilityManager
将开始监控变更。