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で検索すると出てくるので探してみてください!