[英]NotificationCenter not working in didSelectRowAt in iOS Swift 3
[英]NotificationCenter is not working from AppDelegate in Swift iOS
我在使用NotificationCenter
时遇到了一个非常愚蠢的问题。
简介:我在我的应用程序中使用Firebase notification
,所以基本上一旦任何用户收到notification
,我们需要将用户导航到特定的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 notification
时,我AppDelegate's userNotificationCenter: didReceive response: method
被调用。 但是我的ViewController.swift
class 方法没有被调用。
请任何人帮助我。 谢谢!
注意:相反,如果我将addObserver
方法添加到我设置为window.rootViewController
的ViewController
class 中,那么一切正常。 我的方法被调用。
我认为这是使用 NotificationCenter 的完全错误的方法,因为首先你必须观察通知,然后只有你可以发布一些东西。 如果 ViewController 不在 memory 中,它就不能听任何东西。 我希望你明白我的意思。 就像跟聋人打招呼一样。 相反,您应该在didReceive response
方法中找到顶部 ViewController 并使用其导航 controller 进行导航。 您可以使用下面的 function 找到最顶层的 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 时它工作的原因是因为它在您发布内容之前位于 memory 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.