0

I am trying to translate the following from Objective-C to Swift, but I'm stuck!

See https://developer.apple.com/documentation/appkit/nsapplicationlaunchusernotificationkey

NSUserNotification *userNotification = [[myNotification userInfo]
    objectForKey:NSApplicationLaunchUserNotificationKey];
    if (userNotification) {
        // The app was launched by a user selection from Notification Center.
    }
sunknudsen
  • 3,986
  • 1
  • 16
  • 34
  • 1
    agree with @matt as we read the questions and try to spend time for a good answer it is hard to keep up when questioners hop around "spaming" the thread with the same question over and over again. So give us some rest to think and give yourself the chance to get good answers. – Ol Sen Nov 09 '20 at 16:28
  • 1
    @sunknudsen i dont know matt personally but i know his answers everywhere in this website. Actually we should keep tidy this website and learning from experienced developers such as matt, Leo, Asperi and so on.. Everyone has not chance work such a good developers in office but in here i feel like i work together with them here..So keep learning Swift and dont be feel like that :) – zeytin Nov 09 '20 at 16:41

1 Answers1

1

The objective-c syntax in your question is fine.
But the Notification it refers to is the one belonging to -applicationDidFinishLaunching:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSUserNotification *userNotification = aNotification.userInfo[NSApplicationLaunchUserNotificationKey];
    if (userNotification) {
        // The app was launched by a user selection from Notification Center.
    }
}

but the API is deprecated. So it in swift it will look like..

func applicationDidFinishLaunching(_ notification: Notification)
    if let response = notification.userInfo?[NSApplication.launchUserNotificationUserInfoKey] as? UNNotificationResponse {
       // evaluate response.notification.request.content
    }
}
Ol Sen
  • 2,358
  • 1
  • 16
  • 26
  • Thanks for your help. I am new to Swift... your answer looks like Objective-C. I am perhaps missing something. – sunknudsen Nov 09 '20 at 16:36
  • That worked, thanks! Is that the right approach to detecting if app was launched using notification vs double clicking it? – sunknudsen Nov 09 '20 at 16:41
  • have a look at [Eric Corners Answer](https://stackoverflow.com/a/41968928/1443038) and [M.Othman](https://stackoverflow.com/a/21611009/1443038) to the same question. – Ol Sen Nov 09 '20 at 17:08