LoginSignup
1

More than 1 year has passed since last update.

デバイスがオフラインの時に処理をしたい~NWPathMonitor~

Last updated at Posted at 2022-04-11

環境

・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 {
    // オフライン時の処理
}

終わりに

以上になります。

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
1