iOS12+에서는 NWPathMonitor로 제공함
단순히 연결/미연결 확인만 할 거라면 아래처럼
import Network
import Combine
final class NetworkMonitor {
private let monitor = NWPathMonitor()
var connection = CurrentValueSubject<Bool?, Never>(nil)
init() {
start()
}
private func start() {
monitor.pathUpdateHandler = { [weak self] path in
var logString = "[NetworkMonitor] "
switch path.status {
case .requiresConnection:
logString += "requires connection"
case .satisfied:
logString += "satisfied"
self?.connection.send(true)
case .unsatisfied:
var reason = ""
if #available(iOS 14.2, *) {
switch path.unsatisfiedReason {
case .cellularDenied: reason = "celluar deined"
case .localNetworkDenied: reason = "local network denied"
case .notAvailable: reason = "not available"
case .wifiDenied: reason = "wifi denied"
@unknown default: reason = "unknown"
}
}
logString += "unsatisfied. reason: \\(reason)"
self?.connection.send(false)
@unknown default:
logString += "unknown"
}
print(logString)
}
monitor.start(queue: DispatchQueue.global())
}
}
Alamofire에서 Reachablility 지원했었음
다르게 인터넷 확인하는 법?
간단히 유명한 웹사이트에 HEAD를 요청해서 실제 값이 오는지 확인하는 방법도 있음