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?

Swift(Storyboard)でインターネットの接続を確認する

Posted at

1.はじめに
iOSアプリでデータベースなどの外部と連携したアプリを作成することがあると思いますが、その際インターネットに接続されていないと不都合な場合があると思います。その際に必要なコードを書いておこうと思います。

2.実装
1つ目のコードは、常にインターネットに接続を確認して、確認できない場合にアラートを表示するものです。(アラート部分で他の処理を追加することもできます!

import UIKit
import Network

class ViewController: UIViewController {
    let monitor = NWPathMonitor()
    let queue = DispatchQueue.global(qos: .background)

    override func viewDidLoad() {
        super.viewDidLoad()
        startNetworkMonitoring()
    }

    func startNetworkMonitoring() {
        monitor.pathUpdateHandler = { [weak self] path in
            DispatchQueue.main.async {
                if path.status != .satisfied {
                    self?.showNoInternetAlert()
                }
            }
        }
        monitor.start(queue: queue)
    }

    func showNoInternetAlert() {
        let alert = UIAlertController(title: "ネットワークエラー",
                                      message: "インターネットに接続されていません。",
                                      preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

2つ目はボタンが押された場合にインターネットへ接続されているかを確認するものです。常に監視する必要がない、データベースに登録する場合などに使用できます!

import UIKit
import Network

class ViewController: UIViewController {
    let monitor = NWPathMonitor()
    let queue = DispatchQueue.global(qos: .background)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(type: .system)
        
        button.setTitle("接続を確認", for: .normal)
        button.addTarget(self, action: #selector(checkNetworkConnection), for: .touchUpInside)
        
        button.translatesAutoresizingMaskIntoConstraints = false
        
        view.addSubview(button)
        
        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            button.widthAnchor.constraint(equalToConstant: 200),
            button.heightAnchor.constraint(equalToConstant: 50)
        ])
    }
    
    
    @objc func checkNetworkConnection() {
        let monitor = NWPathMonitor()
        monitor.start(queue: queue)
        monitor.pathUpdateHandler = { [weak self] path in
            DispatchQueue.main.async {
                if path.status != .satisfied {
                    self?.showNoInternetAlert()
                } else {
                    print("接続されています")
                }
            }
            monitor.cancel()
        }
    }
    
    func showNoInternetAlert() {
        let alert = UIAlertController(title: "ネットワークエラー",message: "インターネットに接続されていません。",preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

Simulator Screenshot - iPhone 16 Pro - 2025-02-18 at 19.20.22.png

3.おわりに
できるだけ毎日、現在働いている自社開発会社のアプリの修正した機能を公開していくのでよろしくお願いします。
合わせて私がiOS,Androidアプリを開発したIDNectというゲームのIDを友達などと共有できるアプリをよろしくお願いします。
https://idnect.com

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?