8

In a Swift AppDelegate class, you get the following method:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // ...code...
    return true
}

The launchOptions: [NSObject: AnyObject]? parameter is an optional. In Objective-C this is passed as an NSDictionary. I'm looking to extract the UIApplicationLaunchOptionsRemoteNotificationKey from it. Here's how it's done in Objective-C:

NSDictionary *remoteNotification = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];

if (remoteNotification)
{
    // ...do stuff...
}

How would you go about doing that in Swift?

Dave Gallagher
  • 453
  • 4
  • 6

3 Answers3

27

In Swift, you'd do it like this:

if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
    // ...do stuff...
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • 1
    how can I log to the screen what remoteNotification contains. As the app needs to be launched from a push notification while the app attached to xcode? –  Feb 16 '16 at 15:43
  • The best way to see what is actually happening would be to throw a UIAlertView up with the message as the contents of the print statement you would otherwise be logging. – Peter Kaminski Jul 22 '16 at 03:44
1

I handle it in Swift like this:

if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject : AnyObject] {
    // ... do stuff
}
patrickS
  • 3,590
  • 4
  • 29
  • 40
0

I think for Swift 3, it would be like this:

if (launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary) != nil {
    // ...do stuff          
}
Pang
  • 9,564
  • 146
  • 81
  • 122
eyup cimen
  • 71
  • 1
  • 6