Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

xcode7

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

like image 620
Pushpendra Avatar asked Dec 06 '16 07:12

Pushpendra


People also ask

How do I open a new view controller?

To create a new view controller, select File->New->File and select a Cocoa Touch Class. Choose whether to create it with Swift or Objective-C and inherit from UIViewController . Don't create it with a xib (a separate Interface Builder file), as you will most likely add it to an existing storyboard.

How do I change the default view controller?

Open your storyboard. Click on the view controller corresponding to the view that you want to be the default view. Open the Attributes Inspector. Check the Is Initial View Controller check box in the View Controller section.

What is view controllers in IOS?

A view controller acts as an intermediary between the views it manages and the data of your app. The methods and properties of the UIViewController class let you manage the visual presentation of your app. When you subclass UIViewController , you add any variables you need to manage your data in your subclass.

What does view controller do?

A view controller manages a single root view, which may itself contain any number of subviews. User interactions with that view hierarchy are handled by your view controller, which coordinates with other objects of your app as needed. Every app has at least one view controller whose content fills the main window.


2 Answers

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()
    }
like image 88
Dhruv Narayan Singh Avatar answered Nov 14 '22 22:11

Dhruv Narayan Singh


If you app is suspended check the UIApplicationLaunchOptionsRemoteNotificationKey in the dictionary from 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:
    }
    ...
}
like image 28
Thomas G. Avatar answered Nov 14 '22 23:11

Thomas G.