How to Open a Specific View Controller On didReceiveRemoteNotification when application is in back ground

前端 未结 3 1800
眼角桃花
眼角桃花 2021-02-10 21:00

I am implementing a alarm where i am getting pushNotification from server, i am receiving perfect push notification and it is working fine in foreground mode but when applicatio

3条回答
  •  无人共我
    2021-02-10 21:21

    1.Firstly you should Turn On Background Fetch in app "Capabilities" 2. Then use following code in app delegate

    In AppDelegate class add following code:

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
           // print(userInfo)
    let vc = mainStoryBoard.instantiateViewController(withIdentifier: "destinationVC") as! destinationVC
                                self.visibleNavController.pushViewController(vc, animated: true)
        }
    

    For iOS 10 use following code: 1.Import

     import UserNotifications
    

    For foreground fetch

         @available(iOS 10.0, *)
            func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
                var userInfo = NSDictionary()
                userInfo = notification.request.content.userInfo as NSDictionary
                let pay = userInfo as NSDictionary
       let driverLocationVC = mainStoryBoard.instantiateViewController(withIdentifier: "destinationVC") as! destinationVC
                                    self.visibleNavController.pushViewController(driverLocationVC, animated: true)
    
    
        }
    

    For the background

     @available(iOS 10.0, *)
        func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
            print("Userinfo \(response.notification.request.content.userInfo)")
    
    
            var userInfo = NSDictionary()
            userInfo = response.notification.request.content.userInfo as NSDictionary
            print(userInfo)
        let driverLocationVC = mainStoryBoard.instantiateViewController(withIdentifier: "DriverLocationVC") as! DriverLocationVC
                                self.visibleNavController.pushViewController(driverLocationVC, animated: true)
    }
    

    For device token fetch

     func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
            print("Got token data! \(tokenString)")
    
            UserDefaults.standard.set(tokenString, forKey: "device_token")
            UserDefaults.standard.synchronize()
        }
    

提交回复
热议问题