如何获取网络更改通知(连接,断开连接,更改)

时间:2015-10-05 11:34:55

标签: ios objective-c networking

在我的应用中,我必须在网络发生变化时发出警报,例如当应用程序连接或断开连接或更改(wifi到数据)网络时。

但是通过到达网址找到它似乎很昂贵。

iOS中是否有可用的公共API。

4 个答案:

答案 0 :(得分:3)

查看此官方Apple documentation

使用可访问性,您可以识别连接类型。

还有一个关于如何检测更改以及现在为ARC更新文档的完整示例。

我希望这可以帮到你

答案 1 :(得分:1)

我遵循了本教程

https://www.youtube.com/watch?v=wDZmz9IsB-8

信用-> Vasil Nunev

下载此类并导入我的项目-> Reachability.swift

https://github.com/ashleymills/Reachability.swift

(Reachability.swift)->解压缩-> Sources / Reachability.swift

这是我的视图控制器

import UIKit

class ViewController: UIViewController {

let reachability =  Reachability()!

override func viewDidLoad() {
    super.viewDidLoad()

    reachability.whenReachable = { _ in
        DispatchQueue.main.async {
            self.view.backgroundColor = UIColor.green
        }
    }

    reachability.whenUnreachable = { _ in
        DispatchQueue.main.async {
            self.view.backgroundColor = UIColor.red
        }
    }

    NotificationCenter.default.addObserver(self, selector: #selector(internetChanged), name: Notification.Name.reachabilityChanged , object: reachability)
    do{
        try reachability.startNotifier()
    } catch {
        print("Could not strat notifier")
    }
}

@objc  func internetChanged(note:Notification)  {
    let reachability  =  note.object as! Reachability
    if reachability.isReachable{
        if reachability.isReachableViaWiFi{
            self.view.backgroundColor = UIColor.green
        }
        else{
            DispatchQueue.main.async {
                self.view.backgroundColor = UIColor.orange
            }
        }
    } else{
        DispatchQueue.main.async {
            self.view.backgroundColor = UIColor.red
        }
    }
}
}

答案 2 :(得分:0)

答案 3 :(得分:0)

如果您在应用程序中使用 Alamofire,则可以使用它的 NetworkReachabilityManager.swift 类来侦听网络连接。

这是一段代码。

@discardableResult
open func startListening(onQueue queue: DispatchQueue = .main,
                             onUpdatePerforming listener: @escaping Listener) -> Bool {
     stopListening()
     $mutableState.write { state in
         state.listenerQueue = queue
         state.listener = listener
     }

     var context = SCNetworkReachabilityContext(version: 0,
                                                   info: Unmanaged.passUnretained(self).toOpaque(),
                                                 retain: nil,
                                                release: nil,
                                        copyDescription: nil)
     let callback: SCNetworkReachabilityCallBack = { _, flags, info in
         guard let info = info else { return }
         let instance = Unmanaged<NetworkReachabilityManager>.fromOpaque(info).takeUnretainedValue()
            instance.notifyListener(flags)
     }

     let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue)
     let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context)

     // Manually call listener to give initial state, since the framework may not.
     if let currentFlags = flags {
        reachabilityQueue.async {
            self.notifyListener(currentFlags)
        }
     }

     return callbackAdded && queueAdded
}

/// Stops listening for changes in network reachability status.
open func stopListening() {
    SCNetworkReachabilitySetCallback(reachability, nil, nil)
    SCNetworkReachabilitySetDispatchQueue(reachability, nil)
    $mutableState.write { state in
        state.listener = nil
        state.listenerQueue = nil
        state.previousStatus = nil
    }
}

您也可以改用 Apple 的 SCNetworkReachbility 类。