如果连接互联网,我如何解除视图控制器

时间:2016-12-10 13:59:15

标签: ios swift reachability

我试图解除视频控制器,如果互联网连接。当没有互联网时,它会呈现我的noInternetViewController但是当我重新连接到互联网时,noInternetViewController视图并没有被解雇。

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: ReachabilityChangedNotification, object: reachability)
}

func reachabilityChanged(note: NSNotification) {
    let reachability = note.object as! Reachability

    if reachability.isReachable {
        if noInternet == true {
            DispatchQueue.main.async {
                self.noInternet = false
                self.dismiss(animated: true, completion: nil)
            }
        }
    } else {
        noInternet = true
        if noInternet == true {
            DispatchQueue.main.async {
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let noInternetViewController = storyboard.instantiateViewController(withIdentifier: "NoInternetViewController") as! NoInternetViewController
                noInternetViewController.modalPresentationStyle = UIModalPresentationStyle.overFullScreen
                self.present(noInternetViewController, animated: true, completion: nil)
            }
        }

    }
}

和NoInternetViewController:

import UIKit

class NoInternetViewController: UIViewController {

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

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

NoInternetViewController中,您也可以为其添加Observer。当您收到连接时,发布通知以触发它的选择器以解除其自身。

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(receivedConnection), name: NSNotification.Name.init(rawValue: "ReceivedConnection"), object: nil)
}

func receivedConnection() {
    self.dismiss(animated: true, completion: nil)
}