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

【Swift】NWPathMonitor, NotificationCenterを使って、オフラインのときにアラートを表示する

Last updated at Posted at 2023-05-02

はじめに

オンライン・オフラインで起動する画面を条件分岐する処理は実装した経験はあった。
今回、アラートを使って、通信状況をユーザーに伝える機能を実装したので、備忘録として記録。

以下の処理を実装した。
①オンライン, オフラインをAppDelegateで監視する
②通信環境が切り替わったら、ViewControllerNotificationCenterを使って、通知を受け取る

実装

①オンライン, オフラインをAppDelegateで監視する

NotificationCenterを使って、オンライン、オフラインをViewControllerに通知。

AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        Network.shared.setUp()
        Router.shared.showRoot(window: UIWindow(frame: UIScreen.main.bounds))
        
        return true
    }
}
Network.swift
import Network
import Foundation

class Network {
    static let shared: Network = .init()
    private let queue = DispatchQueue(label: "バンドル名(被らなければ何でもOK)")
    private let monitor = NWPathMonitor()
    
    private init() {}
    
    func setUp() {
        monitor.pathUpdateHandler = { path in
            if path.status == .unsatisfied {
                DispatchQueue.main.async {
                    NotificationCenter.default.post(name: .offlineNotifyName, object: nil)
                }
            } else {
                DispatchQueue.main.async {
                    NotificationCenter.default.post(name: .onlineNotifyName, object: nil)
                }
            }
        }
        
        monitor.start(queue: queue)
    }
    
    func isOffline() -> Bool {
        return monitor.currentPath.status == .unsatisfied
    }
}

②通信環境が切り替わったら、ViewControllerNotificationCenterを使って、通知する

NotificationCenter.default.addObserverでオンライン、オフラインの状態をAppDelegateから受け取る

ViewController.swift
final class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(offline),
            name: .offlineNotifyName,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(online),
            name: .onlineNotifyName,
            object: nil
        )
    }
}

@objc private extension ViewController {
    func online() {
       // アラートを閉じる
    }
    
    func offline() {
       // アラートを表示する
    }
}

プレビュー

まとめ

APIを叩く処理を行う前に、ユーザーにアラートを表示すると親切かも

参考リンク

NotificationCenter | Apple Developer Documentation
NWPathMonitor | Apple Developer Documentation
【Swift】NWPathMonitorを使ったネットワーク監視方法について - Qiita
【Swift】NotificationCenterの使い方 - Qiita

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