Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get custom Push Notification value from launchOptions with swift?

I'm building an app with Swift that receives push notifications. I am sending custom values inside the JSON.

I am opening the app through the notification, so I know that I have to do this inside "didFinishLaunchingWithOptions" and read the value from "launchOptions".

How can I read those values and use them on my app.

Many thanks.

like image 475
Aerofan Avatar asked Apr 08 '15 03:04

Aerofan


2 Answers

Here's what works for me in SWIFT 2 when your app is not launched. The code is not quite elegant because of the optional bindings. But it works.

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

    // if launched from a tap on a notification
    if let launchOptions = launchOptions {
        if let userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] {
            if let action = userInfo["action"], id = userInfo["id"] {
                let rootViewController = self.window!.rootViewController as! ViewController
                let _ = setTimeout(5.0, block: { () -> Void in
                    rootViewController.openNotification(action as! String, id: id as! String)
                })

            }
        }
    }
    return true
}
like image 92
Oliver Zhang Avatar answered Oct 07 '22 15:10

Oliver Zhang


In the application:didReceiveRemoteNotification:fetchCompletionHandler, The custom data is in passed on to the didReceiveRemoteNotification, which is an NSDictionary. The details that you want to retrieve is probably on the "aps" key of the userInfo.

func application(application: UIApplication, didReceiveRemoteNotification userInfo: NSDictionary!)
{
    var notificationDetails: NSDictionary = userInfo.objectForKey("aps") as NSDictionary
}

When the app is not launched, you will need to get it from the application:didFinishedLaunchWithOptions,

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

    if let launchOpts = launchOptions {
      var notificationDetails: NSDictionary = launchOpts.objectForKey(UIApplicationLaunchOptionsRemoteNotificationKey) as NSDictionary
    }

    return true
}

EDIT: Remote Notification Fix syntax

like image 24
Raymond Brion Avatar answered Oct 07 '22 15:10

Raymond Brion