【问题标题】:Open app in specific view when user taps on push notification with iOS 13 Swift 5当用户使用 iOS 13 Swift 5 点击推送通知时,在特定视图中打开应用程序
【发布时间】:2019-11-21 09:49:59
【问题描述】:

我的应用允许向用户远程推送通知。当用户点击推送通知时,如何在特定的视图控制器中打开它?我希望应用根据收到的推送通知打开并导航到特定的视图控制器。

【问题讨论】:

标签: ios swift ios13 xcode11


【解决方案1】:

您必须使用“ func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool{ :

中的启动选项检查您的应用何时处于关闭状态
 if let option = launchOptions {
    let info = option[UIApplication.LaunchOptionsKey.remoteNotification]
         if (info != nil) {
            self.goAnotherVC()
     }
}

并且在视图中确实加载了你的登陆 VC 设置了观察者

 NotificationCenter.default.addObserver(self, selector: #selector(self.goToVc(notification:)), name:NSNotification.Name(rawValue:identifier), object: nil)

选择器方法:

 @objc func goToVc(notification:Notification) {
     let storyboard = UIStoryboard(name: "Main", bundle: nil)
     let vc = storyboard.instantiateViewController(withIdentifier:"landingVC") as! landingVC
     self.navigationController?.pushViewController(vc, animated: true)  
}

在应用委托中:

func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
     NotificationCenter.default.post(name:NSNotification.Name(identifier), object: userInfo)
  }

【讨论】:

    【解决方案2】:

    此答案适用于 iOS 13+

    在 AppDelegae 中:

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
       
            NotificationCenter.default.post(name: NSNotification.Name(identifier), object: nil)
            completionHandler()
    }
    

    在viewDidLoad的登陆ViewController:

    override func viewDidLoad() {
            super.viewDidLoad()
            
            NotificationCenter.default.addObserver(self, selector: #selector(self.showChatController(notification:)), name:NSNotification.Name(rawValue: "noti"), object: nil)    
    }
    

    在你登陆viewController添加如下选择器方法:

    @objc
    func showChatController(notification: Notification) {
    print("DEBUG: show chat controller here..")
            
    }
    

    【讨论】:

      【解决方案3】:

      您可以在收到通知并且用户点击通知后触发通知。

      与通知一起,您可以传递稍后用于识别您需要导航到哪个视图控制器的值。

      创建一个负责所有推送通知导航处理的类。您可以将其命名为 PushNotificationHandler。让 PushNotificationHandler 处理程序负责导航到视图控制器的所有逻辑。

      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
      } 
      
      • 使用上述委托方法从深层链接中获取值
      • 使用值触发通知
      • 在 PushNotificationHandler 类中处理通知

      【讨论】:

      • 如果用户已经启动应用并且应用正在后台运行,则不会调用上述方法。
      猜你喜欢
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      相关资源
      最近更新 更多