如何测试 iOS 中的可达性并重试连接?

How to test reachability in iOS and retry to connect?

我想测试当用户在登录时失去连接并提示他们尝试重新连接时的可达性。

首先,我尝试使用 when unreachable 闭包并显示 UIalert says "Please check your internet connection and try again." with "Retry" action to try retry to test the connection if not connection shows the message else "have a connection " 删除 UI 警报。

import UIKit

class BaseTabBarViewController: UITabBarController {

    let network = NetworkManager.sharedInstance

    override func viewDidLoad() {
        super.viewDidLoad()

        network.reachability.whenUnreachable = { reachability in
            self.showOfflinePage()
        }
    }

    func retryConnection(alert: UIAlertAction!){
        print("test connection ")
        // if no connction found show try agine
        //else connction

    }

    func showOfflinePage(){

        DispatchQueue.main.async {
            // create the alert
            let alert = UIAlertController(title: "Connectivity Error", message: "Please check your internet connection and try again.", preferredStyle: UIAlertController.Style.alert)

            // add an action (button)
            alert.addAction(UIAlertAction(title: "Retry", style: UIAlertAction.Style.default, handler: self.retryConnection))

            // show the alert
            self.present(alert, animated: true, completion: nil)
        }
    }
}

您是否尝试过使用 iphone 的开发者选项(在设置中)? 它可以让您模拟不良连接。

有一堆可达性 pods 可用。最常用的一种是 Alamofire。以下是存储库的链接以及如何使用它的示例。

https://github.com/Alamofire/Alamofire/blob/master/Source/NetworkReachabilityManager.swift

https://medium.com/@abhimuralidharan/checking-internet-connection-in-swift-3-1-using-alamofire-58ae45719f5