Search code examples
iosswiftuiviewbackgroundforeground

password view when app come back foreground from background


I am developing an app that need password when app first launch or come back from background to foreground. First launch is easy. But when app back to foreground from background ,after input password ,how to back to the view last visited? Help me please! I want to add a password UIView in appDelegate at top of all , but i don't know how to do it. Is this right way ?

let pwview = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
pwview.backgroundColor = UIColor.black
UIApplication.shared.keyWindow?.addSubview(pwview)

this does not work.


Solution

  • You can use the app delegate's method to handle this.

    func applicationWillEnterForeground(_ application: UIApplication) {
       // Called when app comes to foreground
    }
    
    extension UIApplication {
    
    class func topViewController(base: UIViewController? = (UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController) -> UIViewController? {
    if let nav = base as? UINavigationController {
      return topViewController(base: nav.visibleViewController)
    }
    if let tab = base as? UITabBarController {
      if let selected = tab.selectedViewController {
        return topViewController(base: selected)
      }
    }
    if let presented = base?.presentedViewController {
      return topViewController(base: presented)
    }
    return base
    }
    
    }
    

    You can use the above method from app delegate to get the top view controller and present over it.