How to open a special viewing controller On didReceiveRemoteNotification when the application is in the background

I implement an alarm when I get pushNotification from the server, I get a great push notification and it works fine in the foreground, but when the application is entered in the background, it only receives the push notification, but it doesn’t load the view I want for downloads

Please check the code below

func registerForPushNotifications(application: UIApplication) {
    let notificationSettings = UIUserNotificationSettings(
        forTypes: [.Badge, .Sound, .Alert], categories: nil)
    application.registerUserNotificationSettings(notificationSettings)
}

This method calling from didFinishLaunchingWithOptions

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != .None {
        application.registerForRemoteNotifications()
    }
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""
    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }
    NSUserDefaults.standardUserDefaults().setObject(tokenString, forKey: "deviceToken")
}

This is the final method.

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        print(userInfo)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let navigationController = storyboard.instantiateViewControllerWithIdentifier("AlarmDetailsController") as! AlarmDetailsController
        //let dVC:AlarmDetailsController = navigationController.topViewController as! AlarmDetailsController
        navigationController.isPushNotification = true
        self.window?.rootViewController?.presentViewController(navigationController, animated: true, completion: {})        
}

Please help me with this problem. Remember my application works great in foreground mode.

+4
source share
3 answers

1. , Background Fetch "" 2.

AppDelegate :

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)
    }

iOS 10 : 1.Import

 import UserNotifications

     @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)


    }

 @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)
}

 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()
    }
+4

, UIApplicationLaunchOptionsRemoteNotificationKey application:didFinishLaunchingWithOptions

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    ...

    // Check if launched from notification
    if let userInfo = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {

        // handle your notification like in application:didReceiveRemoteNotificatioUserInfo:
    }
    ...
}
+2

Xcode

enter image description here

: Foreground, Background, Killed, .

1. Foreground. , , , . , .

2. . , , didReceiveRemoteNotification, , , .

3. Killed. , push- , , didReceiveRemoteNotification , .

, ? , , , .

, , , , , . didReceiveRemoteNotification , .

:

https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

push- json

content-available : 1 

, , , .

:

{apns : [],
data : [
   "Navigate" : "Home"
   ]}

didReceiveRemoteNotification,

if let aps = userInfo["data"] as? NSDictionary{
      // get the "Home" data and do navigation here
      // You might need to instantiate storyboard of the specific view controller which you want to go as RootViewController
}

, , , , push- . , .

0

Source: https://habr.com/ru/post/1662926/


All Articles