IOS-Swift开发基础——检测网络状态

检测网络状态可以用Apple-Reachability的例子里的Reachability类(objective-c),拷贝到我们的项目里,然后导给Swift用。

另外,github上也有个Swift版本的Reachability:
https://github.com/ashleymills/Reachability.swift

将里面的Reachability.swift扒过来,加入我们的工程中。然后如下使用:

class ViewController: UIViewController {
    
    var reachability: Reachability?
    
    @IBAction func onButtonClicked(sender: AnyObject) {
        reachability!.stopNotifier()
        NSNotificationCenter.defaultCenter().removeObserver(
            self,
            name: ReachabilityChangedNotification,
            object: reachability
        )
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        do {
            reachability = try Reachability.reachabilityForInternetConnection()
        } catch {
            print("unable to create Reachability")
            return
        }
        
        if reachability!.isReachableViaWiFi() {
            print("连接类型:WiFi")
        } else if reachability!.isReachableViaWWAN() {
            print("连接类型:移动网络")
        } else {
            print("连接类型:没有网络连接")
        }
        
        NSNotificationCenter.defaultCenter().addObserver(
            self,
            selector: "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() {
            if reachability.isReachableViaWiFi() {
                print("当前连接为WiFi")
            } else {
                print("当前连接为蜂窝数据")
            }
        } else {
            print("当前无连接")
        }
    }
}
    原文作者:RichardXG
    原文地址: https://segmentfault.com/a/1190000004662843
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞