LoginSignup
151
94

More than 3 years have passed since last update.

iOSのネットワーク接続状態の検出にはReachabilityよりシンプルなNWPathMonitorを使いましょう。

Last updated at Posted at 2020-08-14

iOSでネットワーク接続状態の取得といえばReachabilityを使うといった印象が強くありませんか。

Reachabilityを使うには、まず
https://developer.apple.com/library/archive/samplecode/Reachability/Introduction/Intro.html
からApple の提供しているサンプルコードをダウンロードして・・・なんて手間がありましたが、もっと手軽に利用できるApple標準のクラスがありました。

簡単にネットワーク接続のモニタリングが可能

NWPathMonitor

ネットワークの接続状態やネットワークインターフェースなどの情報をモニタリングできるNetwork frameworkのクラス。iOS 12.0以降から利用可能。
https://developer.apple.com/documentation/network/nwpathmonitor

実装ステップ

利用箇所でまずフレームワークをインポートしておきましょう。

import Network

モニタリング用クラスのインスタンス化

解放されるとコールバックが受け取れないので、ViewControllerのプロパティなどとして保持しておきましょう。


let monitor = NWPathMonitor()

requiredInterfaceType引数を指定して、ネットワークインターフェース別にモニタリングすることも可能です。

let wifiMonitor = NWPathMonitor(requiredInterfaceType: .wifi)

サポートしているインターフェースのタイプは以下に記載があります。
https://developer.apple.com/documentation/network/nwinterface/interfacetype

ネットワーク接続状態の変更をハンドリングする


monitor.pathUpdateHandler = { path in
    if path.status == .satisfied {
        // Connected
    }
}

後述しますが、モニタリングは通常バックグラウンドキューで指定して実行されます。
クロージャー内でUIを操作する場合には、メインスレッドで行うようにしましょう。

ネットワーク接続状態のモニタリングを開始する

モニタリングイベントを配信するためのDispatchQueueを定義して、モニタリングを開始します。


private let queue = DispatchQueue(label: "com.sample")
monitor.start(queue: queue)

ソースコード全体

import UIKit
import Network

final class ViewController: UIViewController {

    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "com.sample")

    override func viewDidLoad() {
        super.viewDidLoad()

        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                print("Connected")
            } else {
                print("Not Connected")
            }
        }

        monitor.start(queue: queue)
    }
}

まとめ

動画で載せたデモアプリの実装ですが、ViewController内を30行前後で書くことができました。
iOS12以降対応ですし、実用性もばっちりですね。
「ネットワーク接続状態の検出にはNWPathMonitor!」が定着すれば良いなと思います。

以上です :tada:
ありがとうございました。

151
94
1

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
151
94