Search code examples
iosswiftreachability

Swift add view to front via appdelegate


Trying to add a subview to the front of the UI via AppDelegate and it's not working. I have a reachability notifier that should add the UIView from a xib when there is no internet connection.

App Delegate code:

func reachabilityChanged(note: Notification) {
    let reachability = note.object as! Reachability
    if !reachability.isReachable {
        print("APP: Network reachable")
        if networkErrorView != nil {
            networkErrorView.removeFromSuperview()
        }
    } else {
        print("ERROR: Network not reachable")
        networkErrorView = NetworkErrorView(frame: CGRect(x: 30, y: self.window!.frame.height / 4, width: self.window!.frame.width - 60, height: self.window!.frame.height / 2))
        UIApplication.shared.keyWindow?.addSubview(networkErrorView)
        UIApplication.shared.keyWindow?.bringSubview(toFront: networkErrorView)
        print("View is showing")
    }
}

The notification does fire and I do get "View is showing" printed to the console. I've tried calling this via dispatchQueue.main.async but this just results in an infinite loop which crashes the app.

Thanks


Solution

  • private func dismissOfflineScreen() {
        if let navigationVC = self.window?.rootViewController?.presentedViewController as? UINavigationController, navigationVC.viewControllers.first is OfflineViewController {
            navigationVC.dismiss(animated: true, completion: nil)
        }
    }
    
    private func presentOfflineScreen() {
        let navigationVC = UINavigationController(rootViewController: OfflineViewController())
        navigationVC.view.backgroundColor = UIColor.clear
        navigationVC.modalPresentationStyle = UIModalPresentationStyle.overFullScreen
        self.window?.rootViewController?.present(navigationVC, animated: true)
    }