7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

端末のネットワーク接続状態教えて?【SwiftUI】

Last updated at Posted at 2023-12-04

はじめに

端末のネットワーク接続状態に応じて処理を切り替えたいことって意外とありますよね。Wi-Fiだけ動画の品質を上げたり、ダウンロードできるようにしたり、オフラインだけ画面を切り替えたり。
接続状態の確認について調べてみたら色々と見つかったので、備忘録として置いておきます。

結論

NWPathMonitorがおすすめです。

使い方

サンプルで端末のネットワーク状態を監視するオブジェクトを作成しています。
まずは、端末がオフラインかオンラインかを判定する処理を記述します。

import Network

class NetworkObserver {
  private let monitor = NWPathMonitor()
  private let queue = DispatchQueue.global(qos: .background) // 使用用途に合わせたqosを指定してください
  
  /// ネットワーク接続状態を監視
  func startMonitoring() {
    monitor.start(queue: queue)
    
    monitor.pathUpdateHandler = { path in
      if path.status == .satisfied {
        print("online")
      } else {
        print("offline")
      }
    }
  }

  /// ネットワーク接続状態の監視を終了
  func stopMonitoring() {
    monitor.cancel()
  }
}

次に端末の接続状態を判定する処理を追加します

import Network

class NetworkObserver {
  private let monitor = NWPathMonitor()
  private let queue = DispatchQueue.global(qos: .background) // 使用用途に合わせたqosを指定してください
  
  /// ネットワーク接続状態を監視
  func startMonitoring() {
    monitor.start(queue: queue)
    
    monitor.pathUpdateHandler = { path in
      if path.status == .satisfied {
        print("online")
      } else {
        print("offline")
      }
      
      // ここから接続状態を判定
      if path.usesInterfaceType(.wifi) {
        print("Wi-Fi networks")
      } else if path.usesInterfaceType(.cellular) {
        print("cellular networks")
      } else if path.usesInterfaceType(.wiredEthernet) {
        print("wired Ethernet networks")
      } else if path.usesInterfaceType(.loopback) {
        print("local loopback networks")
      } else if path.usesInterfaceType(.other) {
        print("virtual networks or networks of unknown types")
      }
    }
  }

  /// ネットワーク接続状態の監視を終了
  func stopMonitoring() {
    monitor.cancel()
  }
}

NWPath.StatusNWInterface.InterfaceTypeといったオブジェクトの詳細は以下の公式記事を参考にしてみてください。

終わりに

接続状態の管理もこれでバッチリです。

7
0
0

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
7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?