我在使用NotificationCenter
时遇到了一个非常愚蠢的问题。
简介:我在应用中使用 Firebase 通知
,因此基本上一旦任何用户收到通知
,我们就需要将用户导航到特定的 ViewController
屏幕。
这是我的代码:
@available(iOS 10, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let paymentStatus = userInfo["message"] as? String {
if paymentStatus == "SUCCESS"{
// handle notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PaymentSuccessfulNotification"), object: nil, userInfo: userInfo)
}
}
completionHandler()
}
}
ViewController.swift viewDidLoad 方法:
NotificationCenter.default.addObserver(self,selector: #selector(paymentSuccessfulNotificationReceived),
name: NSNotification.Name(rawValue: "PaymentSuccessfulNotification"), object: nil)
并声明了这个方法:
@objc func paymentSuccessfulNotificationReceived(notification: NSNotification){
DispatchQueue.main.async {
// Navigate code
let viewController = AppManager.VideoCallStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.navigationController?.pushViewController(viewController, animated: false)
}
}
问题:当我收到 Firebase 通知
时,我的 AppDelegate 的 userNotificationCenter: didReceive response: 方法
被调用。但我的 ViewController.swift
类方法没有被调用。
请任何人帮助我解决这个问题。谢谢!
注意:相反,如果我将我的 addObserver
方法添加到我设置为 window.rootViewController 的
然后一切工作正常。我的方法被调用。ViewController
类中
最佳答案
我认为这是使用NotificationCenter的完全错误的方法,因为首先你必须观察通知然后只有你可以发布一些东西。如果 ViewController 不在内存中,它就无法监听任何内容。我希望你明白我的意思。这就像向聋子打招呼一样。相反,您应该在 didReceive response
方法中找到顶部 ViewController,并使用其导航 Controller 进行导航。您可以使用以下函数来查找最顶层的 ViewController。
extension UIApplication {
/** To find top viewcontroller */
class func topViewController(base: UIViewController? = UIApplication.shared.windows.first { $0.isKeyWindow }?.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
}
}
它在创建 rootViewController 时起作用的原因是因为它在您发布某些内容之前就已经在内存中了。
关于ios - 通知中心无法通过 Swift iOS 中的 AppDelegate 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61147135/