Controlling which view controller loads after receiving a push notification in SWIFT

孤者浪人 提交于 2019-11-28 16:23:35

Updated for Swift 4.2

Like it was said, you want to register to remote notifications in applicationDidLaunchWithOptions :

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let pushSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
    UIApplication.shared.registerUserNotificationSettings(pushSettings)
    UIApplication.shared.registerForRemoteNotifications()
}

There is no way to know in which viewController you will be when you come back from the lockScreen/Background. What I do is I send a notification from the appDelegate. When you receive a remoteNotification, didReceiveRemoteNotification in the appDelegate is called.

 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    let notif = JSON(userInfo) // SwiftyJSON required 

Depending on what your notification contains, you should first make sure it is not nil and then call a notification that will be catched by the viewControllers that should catch this notification. Could look like this, just take it as an example :

if notif["callback"]["type"] != nil{
    NotificationCenter.default.post(name: Notification.Name(rawValue: "myNotif"), object: nil)
    // This is where you read your JSON to know what kind of notification you received, for example :    

}

For example, if you receive a message notification and you have not logged in anymore because the token has expired, then the notification will never be catched in the view controller because it will never be watched.

Now for the part where you catch the notification in the view controller. In the viewWillAppear :

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(self.catchIt), name: NSNotification.Name(rawValue: "myNotif"), object: nil)
}

Now that you added this observer, each time a notification is called in this controller, the function catchIt will also be called. You will have to implement it in every view controller you want to implement a specific action.

func catchIt(_ userInfo: Notification){

    let prefs: UserDefaults = UserDefaults.standard
    prefs.removeObject(forKey: "startUpNotif")

    if userInfo.userInfo?["userInfo"] != nil{
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc: RedirectAppInactiveVC = storyboard.instantiateViewController(withIdentifier: "RedirectAppInactiveVC") as! RedirectAppInactiveVC
        self.navigationController?.pushViewController(vc, animated: true)
    } else {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc: RedirectAppActiveVC = storyboard.instantiateViewController(withIdentifier: "RedirectAppActiveVC") as! RedirectAppActiveVC
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

Don't forget to unsubscribe from the notifications when leaving the view controller, else the viewController, if still in the stack, will catch the notification and execute it (well you might want to that, but it's safer to know what you are going into). So I suggest unsubscribing in the viewWillDisappear:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.removeObserver(self)
}

Doing it this way, you will load the viewController you want. Now we haven't treated all the cases yet. What if you haven't opened your application yet. Obviously, no UIViewController has been loaded, and none of them will be able to catch the notification. You want to know if you received a notification in didFinishLaunchingWithOptions: in the appDelegate. What I do is:

let prefs: UserDefaults = UserDefaults.standard
if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
    prefs.set(remoteNotification as! [AnyHashable: Any], forKey: "startUpNotif")
    prefs.synchronize()
}

Now, you have set a preference saying the application was started using a remote notification. In the controllers that should be loaded first in your application, I suggest doing the following in the viewDidAppear:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let prefs: UserDefaults = UserDefaults.standard
    if prefs.value(forKey: "startUpNotif") != nil {
        let userInfo: [AnyHashable: Any] = ["inactive": "inactive"]
        NotificationCenter.default.post(name: Notification.Name(rawValue: "myNotif"), object: nil, userInfo: userInfo as [AnyHashable: Any])
    }
}

Hope it helps. I also made a GitHub repository to illustrate with local notifications : Local Notifications Observer Pattern (similar to Remote notifications). A similar logic can be implemented using the root view Controller Local Notifications Root Pattern, I personally think it will depend on what you want to implement.

These examples are here to illustrate how it can be simply implemented. With bigger projects, you will end up with more complex architectures such as coordinators that that internally utilize similar mechanisms.

In addition to @NickCatib's answer, to find out if you received a notification while your app is running and if so, in the foreground or background you need to use this method in your AppDelegate:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {


// You can determine your application state by
if UIApplication.sharedApplication().applicationState == UIApplicationState.Active {

// Do something you want when the app is active

} else {

// Do something else when your app is in the background


}
}

When you run you application, you are calling applicationDidLaunchWithOptions:

UIApplication.sharedApplication().registerUserNotificationSettings ( UIUserNotificationSettings(forTypes: (UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound), categories: nil))



if( launchOptions != nil){
    var notificationDict: AnyObject? = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey]
    if(notificationDict != nil){
        handleNotification(notificationDict! as! [NSObject : AnyObject])
    }

}

Here, you have handleNotification which is basicly my custom function where I extract data from the notification and use that information to show corresponding controller.

Here is an example of that:

let notificationType = userInfo["aps"]!["alert"]!!["some-key-I-Need"]! as! String
var storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = storyboard.instantiateInitialViewController() as! MyViewController
self.window?.rootViewController  = mainViewController

I found all the answers above to be very helpful. Yet, the most voted did not worked for me when the app is deactivated. Later a tried to implement the answers from @NickCatib and @thefredelement combined and they generated an error when executing storyboard.instantiateInitialViewController() - "Could not cast value of type 'UINavigationController'". I found out that this happened because I have a storyboard file with NavController as rootViewController. To solve this issue I created a new Navigation Controller, and that worked with a problem: i lost the correct navigation for the app, and the view didn't even showed the back button. The answer to my problems was to use @NickCatib and @thefredelement answers, but to instantiate the view using an identifier and to push it, using the rootViewController as an UINavigationController, as shown below.

let rootViewController = self.window?.rootViewController as! UINavigationController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mvc = storyboard.instantiateViewControllerWithIdentifier("MyViewController") as! 
             MyViewController
rootViewController.pushViewController(mvc, animated: true)

This worked fine for me, and I didn't lose the correct navigation properties for the app.

complementary information to the previous answers.

Depending on your state you can change your logic. Within the method didReceiveRemoteNotification :

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {}

you can can do a switch like this

let state = UIApplication.sharedApplication().applicationState switch state { case UIApplicationState.Active: case UIApplicationState.Inactive: case UIApplicationState.Background: }

an perform the actions you want based on the current state the app is in.

Jorge Cardenas

Swift Rabbit answer is the best.

I would add that is still missing when the app comes from being closed to active state.

You can add in AppDelegate, inside didFinishedLaunchingWithOptions:

if let notification = launchOptions?[.remoteNotification] as? [AnyHashable : Any] {

            notificationsUserInfo = notification as [AnyHashable : Any]
            serveNotifications = true

        }

You could create a global variable or userdefault with the value of the notification, and use a flag to let the rest of the app that there is a notification.

Once the mainViewController is visible, you can perform actions to process the notifications.

override func viewDidAppear(_ animated: Bool) {
        if serveNotifications {
      notificationManager.sharedInstance.processNotification(userInfo: notificationsUserInfo)

            serveNotifications = false

        }

    }

Take care.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!