4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOSのネットワーク状態を取得する

4
Last updated at Posted at 2021-03-24

iOSのネットワーク状態を取得するには、AppleのサンプルコードにあるReachabilityが有名でしたが、iOS13からNWPathMonitorってのが使えるようになってました(知らなかった)

func getNetworkInfo(completionHandler: @escaping (String) -> ()) {
    let monitor = NWPathMonitor()
    monitor.pathUpdateHandler = { path in
        // 接続先もわかる
        if path.usesInterfaceType(.wifi) {
            // Correctly goes to Wi-Fi via Access Point or Phone enabled hotspot
            os_log("Path is Wi-Fi", type: .info)
        } else if path.usesInterfaceType(.cellular) {
            os_log("Path is Cellular", type: .info)
        } else if path.usesInterfaceType(.wiredEthernet) {
            os_log("Path is Wired Ethernet", type: .info)
        } else if path.usesInterfaceType(.loopback) {
            os_log("Path is Loopback", type: .info)
        } else if path.usesInterfaceType(.other) {
            os_log("Path is other", type: .info)
        }
    }
    monitor.start(queue: DispatchQueue(label: "nwpathmonitor.queue"))
}

僕はWi-Fi時のGatewayのアドレスを知りたかったので、こんなふうにしました。

func getGatewayInfo(completionHandler: @escaping (String) -> ()) {
    let monitor = NWPathMonitor(requiredInterfaceType: .wifi)
    monitor.pathUpdateHandler = { path in

        if let endpoint = path.gateways.first {
            switch endpoint {
            case .hostPort(let host, _):
                let remoteHost = host.debugDescription
                print("Gateway: \(remoteHost)")
                // Use callback here to return the ip address to the caller
                completionHandler(remoteHost)
            default:
                break
            }
        } else {
            print("Wifi connection may be dropped.")
        }
    }
    monitor.start(queue: DispatchQueue(label: "nwpathmonitor.queue"))
}

監視を止める場合は、

monitor.cancel()

です。stopではないので注意。
他にもNWPathMonitorで検索すると出てくるので探してみてください!

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?