所以,我在我的AppDelegate中有以下内容。
当我关闭WIFI但在初次运行后不会做出反应时,它会通知我。
我过去一直在工作。 br />我正在使用Xcode 8的swift 3以及此版本的swift和xCode的可达性。
我希望得到一个解决方案。
谢谢。
var reachability: Reachability?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.reachability = Reachability()
NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability)
do {
try self.reachability?.startNotifier()
} catch {
print("Unable to start Notifier")
}
return true
}
func reachabilityChanged(_ note:Notification){
print("is in here")
let reachability = note.object as! Reachability
if reachability.isReachable{
print("is Reachable")
// self.amConnected.text = "YES"
//self.amConnected.fadeOut(duration: 2.0)
}else{
print("IsNotReachable")
//self.amConnected.text = "No"
//self.amConnected.fadeIn(duration: 2.0)
}
print("Changed status")
}
答案 0 :(得分:4)
Swift 3中的Reachability有一些变化。下载最新的Reachability.swift
文件并将其添加到项目中。 Link
对于 Swift 2.x 代码,请检查我的回答here
Swift 3.x代码
现在在你的AppDelegate
中取一个Reachability
类对象
private var reachability:Reachability!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//Network Reachability Notification check
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged), name: ReachabilityChangedNotification, object: nil)
self.reachability = Reachability.init()
do {
try self.reachability.startNotifier()
} catch {
}
return true
}
reachabilityChanged
方法定义
//MARK:- Network Check
func reachabilityChanged(notification:Notification) {
let reachability = notification.object as! Reachability
if reachability.isReachable {
if reachability.isReachableViaWiFi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
} else {
print("Network not reachable")
}
}
每当用户从Wifi切换到Cellular时,或者当网络连接和断开连接时,或者反之亦然,这将始终被调用。
在我的情况下正常工作。
阅读documentation了解 Swift 3重大变化部分
的更多详细信息为您制作样品
https://www.dropbox.com/sh/bph33b12tyc7fpd/AAD2pGbgW3UnqgQoe7MGPpKPa?dl=0
答案 1 :(得分:0)
尝试将nil
传递给object
中的addObserver
参数。另外,对于Swift 3,我不得不用self.reachability = Reachability.forInternetConnection()