1

检测网络状态可以用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
337 声望19 粉丝