在Swift中使用Reachability,NSNotification和Network Link Conditioner检测networking连接变化

我正在尝试将networking连接检测function集成到我的应用程序中,但是似乎在某些地方我犯了一个错误,因为我的networking更改没有被检测/打印到控制台中。

正如在文章中提到的,我目前正在使用以下这些类和工具来完成这项工作:

  1. 可达性{.h, .m}
  2. NSNotificationCenter
  3. networking链接调节器

AppDelegate.Swift中 ,我设置了NSNotificationCenter来检测更改:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // ... // A: Checks if the device is connected to the internet var defaultCenter: Void = NSNotificationCenter().addObserver(self, selector:"checkForReachability", name: kReachabilityChangedNotification, object: nil) 

}

在同一个AppDelegate类中,我也创build了这个函数,在有变化时触发:

 func checkForReachability () { var networkReachability = Reachability.reachabilityForInternetConnection() networkReachability.startNotifier() var remoteHostStatus = networkReachability.currentReachabilityStatus() if (remoteHostStatus.value == NotReachable.value) { println("Not Reachable") } else if (remoteHostStatus.value == ReachableViaWiFi.value) { println("Reachable via Wifi") } else { println("Reachable") } } 

但是,使用Network Link Conditioner来处理和模拟条件变化时,我无法看到在控制台中反映的任何变化。 任何帮助将膨胀!

您必须先创buildReachability对象, 然后才能从中接收通知。 此外,一定要调用您创build的Reachability对象上的startNotifier()方法。 这将是如何在应用程序委托中执行的一个示例:

 class AppDelegate: UIResponder, UIApplicationDelegate { private var reachability:Reachability!; func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkForReachability:", name: kReachabilityChangedNotification, object: nil); self.reachability = Reachability.reachabilityForInternetConnection(); self.reachability.startNotifier(); } func checkForReachability(notification:NSNotification) { // Remove the next two lines of code. You cannot instantiate the object // you want to receive notifications from inside of the notification // handler that is meant for the notifications it emits. //var networkReachability = Reachability.reachabilityForInternetConnection() //networkReachability.startNotifier() let networkReachability = notification.object as Reachability; var remoteHostStatus = networkReachability.currentReachabilityStatus() if (remoteHostStatus.value == NotReachable.value) { println("Not Reachable") } else if (remoteHostStatus.value == ReachableViaWiFi.value) { println("Reachable via Wifi") } else { println("Reachable") } } } 

我build议你看一下NSNotificationCenter和NSNotification的文档。 这样,下次出现这种情况时,您将更熟悉如何处理通知。

Swift 3

 NotificationCenter.default.addObserver(self, selector:Selector(("checkForReachability:")), name: NSNotification.Name.reachabilityChanged, object: nil) let reachability: Reachability = Reachability.forInternetConnection() reachability.startNotifier() 

适用于swift 2.1和XCode 7:

尝试这个第三方高度评价Reachablity类

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { // Allocate a reachability object self.reach = Reachability.reachabilityForInternetConnection() // Tell the reachability that we DON'T want to be reachable on 3G/EDGE/CDMA self.reach!.reachableOnWWAN = false // Here we set up a NSNotification observer. The Reachability that caused the notification // is passed in the object parameter NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: nil) self.reach!.startNotifier() return true } //Reachbality Notification Response func reachabilityChanged(notification: NSNotification) { if self.reach!.isReachableViaWiFi() || self.reach!.isReachableViaWWAN() { print("Service avalaible!!!") } else { print("No service avalaible!!!") AppHelper.showALertWithTag(0, title: constants.AppName.rawValue, message: "Please Check Your Internet Connection!", delegate: self, cancelButtonTitle: "OK", otherButtonTitle: nil) } } 

更新了Swift 2的AR Younce答案:

 func checkForReachability(notification:NSNotification) { if let networkReachability = notification.object as? Reachability { let remoteHostStatus = networkReachability.currentReachabilityStatus() if (remoteHostStatus == NotReachable) { print("Not Reachable") } else if (remoteHostStatus == ReachableViaWiFi) { print("Reachable via Wifi") } else { print("Reachable") } } else { print("Unknown") } } 

Swift 2.0 – 使用可达性检查networking,NSNotification

AppDelegate.swift

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(self.checkNetworkStatus(_:)), name: "ReachabilityChangedNotification", object: nil); do{self.reachability = try Reachability.reachabilityForInternetConnection()}catch{} do{try self.reachability.startNotifier()}catch{} self.checkNetworkStatus() return true } 

声明networkStatusvariables

 var networkStatus : Reachability.NetworkStatus! 

checkNetworkStatus()函数

 func checkNetworkStatus() { networkStatus = reachability.currentReachabilityStatus if (networkStatus == Reachability.NetworkStatus.NotReachable) { print("Not Reachable") } else { print("Reachable") } } 

OtherClass.Swift

 let delegate = UIApplication.sharedApplication().delegate as! AppDelegate if (delegate.networkStatus!=Reachability.NetworkStatus.NotReachable) { // Call Webservice } else { delegate.checkNetworkStatus() //Not Reachable print } 

而不是用观察者callback污染AppDelegate.swift ,我build议只将观察者添加到相关的视图控制器中。

AppDelegate.swift

 import ReachabilitySwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var reachability: Reachability? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool { self.reachability = Reachability() do { try reachability?.startNotifier() } catch { print( "ERROR: Could not start reachability notifier." ) } return true } class func sharedAppDelegate() -> AppDelegate? { return UIApplication.shared.delegate as? AppDelegate } // Remaining functions } 

ViewController示例:

 class ExampleVC: UIViewController { override func viewDidLoad() { // Add reachability observer if let reachability = AppDelegate.sharedAppDelegate()?.reachability { NotificationCenter.default.addObserver( self, selector: #selector( self.reachabilityChanged ),name: ReachabilityChangedNotification, object: reachability ) } } @objc private func reachabilityChanged( notification: NSNotification ) { guard let reachability = notification.object as? Reachability else { return } if reachability.isReachable { if reachability.isReachableViaWiFi { print("Reachable via WiFi") } else { print("Reachable via Cellular") } } else { print("Network not reachable") } } } 

Swift 3

1)在您的项目中安装pod'ReachabilitySwift'

2)在AppDelegate.swift中

让reachability =可达性()!

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //declare this property where it won't go out of scope relative to your listener //declare this inside of viewWillAppear NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),name: ReachabilityChangedNotification,object: reachability) do{ try reachability.startNotifier() }catch{ print("could not start reachability notifier") } return true } 

3)

  func reachabilityChanged(note: Notification) { let reachability = note.object as! Reachability if reachability.isReachable { if reachability.isReachableViaWiFi { print("Reachable via WiFi") } else { print("Reachable via Cellular") } } else { print("Network not reachable") } }