检测 Internet 连接并显示 UIAlertview Swift 3

Detect Internet Connection and display UIAlertview Swift 3

我正在制作一个应用程序,它通过使用 if else 语句检测是否有互联网连接,当有互联网时,什么都不做,但如果没有互联网连接,则提醒视图说该应用程序需要互联网我设法找到了可达性,但要在我的 viewDidLoad() 上实施,uialertview 似乎无法正常工作。 我正在使用这个:

public class Reachability {
class func isConnectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        [=11=].withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }
    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
    if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
        return false
    }
    let isReachable = flags == .reachable
    let needsConnection = flags == .connectionRequired
    return isReachable && !needsConnection
    }
}

然后在我的视图控制器中 class:

override func viewDidLoad() {
        if Reachability.isConnectedToNetwork() == true
        {
            print("Connected")
        }
        else
        {
            let controller = UIAlertController(title: "No Internet Detected", message: "This app requires an Internet connection", preferredStyle: .alert)
            let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
            let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

            controller.addAction(ok)
            controller.addAction(cancel)

            present(controller, animated: true, completion: nil)
        }
        super.viewDidLoad()
        //...
    }

并且看起来 alertview 没有弹出 有什么建议吗?或帮助? 谢谢

您必须将 AlertController 放在 ViewController 生命周期的 viewDidAppear 方法中,因为在方法 viewDidLoad 和 viewWillAppear 中,您当前的视图仍然不在 window 层次结构中。
如果你想进一步呈现 ViewControllers,比如 AlertController,你需要一个完整加载的视图,你的新 ViewController 可以在其中呈现:

override func viewDidLoad() {
    super.viewDidLoad()
    //ViewControllers view not in the window hierarchy
    // Here you could make further initialization of your views subviews
}

override func viewWillAppear(_ animated: Bool) {
    //ViewControllers view ist still not in the window hierarchy
    //This is the right place to do for instance animations on your views subviews
}

override func viewDidAppear(_ animated: Bool) {
    // ViewControllers view ist fully loaded and could present further ViewController
    //Here you could do any other UI operations
    if Reachability.isConnectedToNetwork() == true
    {
        print("Connected")
    }
    else
    {
        let controller = UIAlertController(title: "No Internet Detected", message: "This app requires an Internet connection", preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
        let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

        controller.addAction(ok)
        controller.addAction(cancel)

        present(controller, animated: true, completion: nil)
    }

}

这是 Apple 文档中关于 ViewController 的内容: UIViewController 方法调用如下:

  • viewDidLoad()—当视图控制器的内容视图(顶部 它的视图层次结构)是从情节提要中创建和加载的。这个 方法用于初始设置。但是,由于视图可能 由于应用程序中的资源有限而被清除,不能保证 它只会被调用一次。
  • viewWillAppear()—适用于任何 您希望始终在视图变为之前发生的操作 可见的。因为视图的可见性可能会被切换或隐藏 在其他视图中,此方法总是在 内容视图出现在屏幕上。
  • viewDidAppear()—适用于任何 您希望在视图变为时立即发生的操作 可见,例如获取数据或显示动画。因为一个 视图的可见性可能会被其他视图切换或遮挡,这 方法总是在内容视图出现后立即调用 屏幕上。

参考:https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson4.html

这就是 Apple 文档中关于 ViewController 的内容:UIViewController 方法的调用方式如下:

  • viewDidLoad()—当创建视图控制器的内容视图(其视图层次结构的顶部)并从故事板加载时调用。此方法用于初始设置。但是,由于应用程序中的资源有限,视图可能会被清除,因此不能保证它只会被调用一次。

  • viewWillAppear() - 适用于您希望始终在视图可见之前发生的任何操作。因为视图的可见性可能会被其他视图切换或遮挡,所以总是在内容视图出现在屏幕上之前立即调用此方法。

//viewDidAppear

    override func viewDidAppear(_ animated: Bool) {
    netTester()
}

//Internet Checker
func netTester() {

    reachability = Reachability.init()
    if ((self.reachability!.connection) != .none) {
        print("Internet is Ok")
    } else{
        print("Internet is nO ok")

        let controller = UIAlertController(title: "No Internet Detected", message: "This app requires an Internet connection", preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
        let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

        controller.addAction(ok)
        controller.addAction(cancel)

        present(controller, animated: true, completion: nil)
    }

    do {
        try reachability!.startNotifier()
    } catch {
        print("Unable to start notifier")
    }
}
  • viewDidAppear()—用于您希望在视图可见时立即发生的任何操作,例如获取数据或显示动画。因为视图的可见性可能会被其他视图切换或遮挡,所以总是在内容视图出现在屏幕上后立即调用此方法。

View Did Load - 第一种方法,当视图第一次加载但未出现在 screen/window 时调用,仅加载。

仅在第一次加载视图时调用一次。

View Did Appear - 在调用 viewWillAppear 之后,将调用 viewDidAppear。这意味着视图现在出现在屏幕上。

当用户从 viewcontroller 移动到另一个视图控制器并返回时调用的次数。

https://developer.apple.com/documentation/uikit/uiviewcontroller/1621423-viewdidappear