【发布时间】:2016-10-13 19:33:56
【问题描述】:
编写需要网络的应用。最初在 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。回到我的应用程序中,我在应用程序委托中得到了这个。
func applicationWillEnterForeground(_ application: UIApplication) {
print("applicationWillEnterForeground")
wifiWorks = Reachability.isConnectedToNetwork()
}
这让我回到原点,所以你无法继续使用该应用程序,因为它需要 WiFi。
我的问题,这种舞蹈有意义吗?还是/是否有更清洁的方法来做到这一点?
【问题讨论】:
-
为什么要让用户有机会访问您应用的“设置”页面?用户无法从该页面打开 WiFi。
标签: ios swift connection wifi reachability