Search code examples
iosswiftxcode7

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


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 application enter in background then it getting only push notification but not loading the view which i want to load

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 for that problem Remember My Application is working fine in foreground mode


Solution

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