当应用程序进入后台和前台时,带有通知中心的登录屏幕,Swift

Posted

技术标签:

【中文标题】当应用程序进入后台和前台时,带有通知中心的登录屏幕,Swift【英文标题】:Present login screen with notification center when app enters background and foreground, Swift 【发布时间】:2021-05-19 08:05:45 【问题描述】:

我有登录屏幕,我想展示它或者只是将它添加到导航中,现在没关系,但每次我的应用程序返回前台时,我仍然不确定我希望它是哪种方式。下面的代码部分有效,它确实启动了人脸 ID,但实际上没有显示整个登录屏幕,我仍然可以看到在进入后台之前打开的最后一个屏幕。我想用登录屏幕隐藏所有内容。当我在 appMovedToBackground 函数中打印 childs 时,会打印正确的视图控制器,这意味着它已添加,但正如我所说,它没有显示,只能看到来自 face id 的图标。下面的代码仅在一个视图控制器上,目前,我希望将其应用于我的所有视图控制器,我应该将功能移动到 appdelegate 吗?提前致谢。

    let notificationCenter = NotificationCenter.default

override func viewDidLoad() 
    super.viewDidLoad()
    
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    notificationCenter.addObserver(self, selector: #selector(appCameToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)


@objc func appMovedToBackground() 
    print("its in background")
    let authVC = AuthViewController()
    navigationController?.topViewController?.addChild(authVC)


@objc func appCameToForeground() 
    print("app enters foreground")
    if let authVC = navigationController?.topViewController?.children.first as? AuthViewController 
    print("willEnterForegroundNotification")
        authVC.checkBiometricsAndStart()
    

【问题讨论】:

【参考方案1】:

这里需要正确添加vc

@objc func appMovedToBackground() 
   print("its in background")
   guard let added = navigationController?.topViewController else  return  
   let authVC = AuthViewController()
   authVC.view.frame = UIScreen.main.bounds
   added.view.addSubview(authVC.view)
   added.addChild(authVC)

关于所有 vcs 都需要它,是的,在 AppDelegate 中实现它是最简单的方法

【讨论】:

谢谢,这确实有帮助,还有一个问题。由于相同的 loginVC 被设置为 root 并且我希望它在应用程序进入前台时显示,在 viewDidLoad 中的 loginVC 中我总是调用面部 ID 的函数,现在,因为它在 viewDidLoad 中,所以当应用程序进入后台时它立即启动 faceId .我应该改变什么,所以当我再次打开应用程序时 faceId 实际上开始,而不是当 loginVC 添加到堆栈时。 @Sh_Khan 不要在viewDidLoad里面调用它在appCameToForeground里面调用它

以上是关于当应用程序进入后台和前台时,带有通知中心的登录屏幕,Swift的主要内容,如果未能解决你的问题,请参考以下文章

当应用程序进入后台时,应用程序在前台使用带有 GPU 的 CoreML 无法切换到 CPU

当应用程序进入前台时,哪个View Controller处于活动状态?

当应用程序进入暂停状态时取消本地通知。(从后台删除)

当应用程序在后台时,推送通知不起作用

推送通知无法正常工作,当应用程序在后台时,Swift

当应用程序在前台时,如何使远程通知出现在通知中心?