管理wifi可达性变化的正确方法是什么?

时间:2016-10-13 19:33:57

标签: ios swift connection wifi reachability

编写需要网络的应用。最初在ViewController中运行一个方法来检查WiFi是否已打开并正常工作。所以我得到了......

wifiWorks = Reachability.isConnectedToNetwork()

这是这样定义的......

var wifiWorks: Bool = false {
  didSet {
    if wifiWorks {
        print("Wifi On")
        NotificationCenter.default.post(name: Notification.Name("WifiBon"), object: nil, userInfo: nil)
    } else {
        print("WiFi Off")
        NotificationCenter.default.post(name: Notification.Name("noWiFi"), object: nil, userInfo: nil)
    }
  }
}

现在,如果noWifi被调用,它会显示一个警报,基本上会进入这样的设置......

 func noWifi(notification:NSNotification) {
    DispatchQueue.main.async {
        //self.navigation.isHidden = true 
        let alert = UIAlertController(title: "Stop", message: "Your iPad isn't connected to the WiFi ...", preferredStyle: UIAlertControllerStyle.alert)
        let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
            guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
                return
            }

            if UIApplication.shared.canOpenURL(settingsUrl) {
                UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                    print("Settings opened: \(success)") // Prints true
                })
            }
        }
        alert.addAction(settingsAction)
        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        alert.addAction(cancelAction)
        self.present(alert, animated: true, completion: nil)
    }
}

此时,我的应用程序不再运行,用户正坐在设置中,并且必须切换回我的应用程序(希望)打开WiFi。回到我的应用程序中,我在app delegate中得到了这个。

func applicationWillEnterForeground(_ application: UIApplication) {
    print("applicationWillEnterForeground")
    wifiWorks = Reachability.isConnectedToNetwork()
}

这让我回到了整整一圈,因此您无法继续使用该应用,因为它需要WiFi。

我的问题,这种舞蹈是否有意义;或者是否有更清洁的方法来做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用Reachability自己的通知,因为它GitHub page建议:

NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),name: ReachabilityChangedNotification,object: reachability)

do{
  try reachability.startNotifier()
}catch{
  print("could not start reachability notifier")
}

回调:

func reachabilityChanged(note: NSNotification) {
    let reachability = note.object as! Reachability
    if !reachability.isReachable {
        //you can show alert here
    }
}

另请注意,只需从控制中心切换wifi切换,用户无需离开应用即可打开/关闭wifi。这就是为什么你不应该只依赖applicationWillEnterForeground方法。