swift3 xcode 8.3.3检查应用程序运行期间的可访问性

时间:2017-08-07 10:54:48

标签: ios swift3 reachability

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")
        }
    }


}

1 个答案:

答案 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将开始监控变更。