環境
・Swift 5.5.2
・Xcode 13.2.1
動機
Firebase等、ネットワーク接続が必須なアプリで、デバイスがオフラインの時にアラートを出したい。etc...
其の一
有名なライブラリにReachability.Swiftというものがあるみたいですが、今回はAppleが標準で用意してくれているNWPathMonitorを使用します。
其の二
シングルトンクラスを作成します。
Network.swift
import Network
final class Network {
static let shared = Network()
private let monitor = NWPathMonitor()
func setUp() {
monitor.start(queue: .global(qos: .background))
}
func isOnline() -> Bool {
return monitor.currentPath.status == .satisfied
}
}
其の三
ネットワーク監視の開始をAppDelegateに記述します。
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Network.shared.setUp()
return true
}
其の四
例としてif文を使っていますが、guard文を使ってオフライン時はこれ以上先に進めないように早期リターンするのも良いと思います。
ViewController.swift
if Network.shared.isOnline() {
// オンライン時の処理
} else {
// オフライン時の処理
}
終わりに
以上になります。