Alex Pelletier
Alex Pelletier

Reputation: 5123

Get initial URL used to launch OS X app

I have a Mac app written in Swift with a custom URL scheme.

If the app is running and opened from a link everything works great. But if the app is not running then then the app does not open to the correct page.

I am registering for notifications like this:

let eventManager = NSAppleEventManager.sharedAppleEventManager()
eventManager.setEventHandler(self, andSelector: "handleGetURLEvent:replyEvent:", forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))

How do I get the url from the initial launch in:

func applicationDidFinishLaunching(aNotification: NSNotification)

Edit 1: In my app delegate I have:

func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?)

This function is called, and works when the app is already open, but does not work when the app is closed.

Upvotes: 1

Views: 1089

Answers (2)

Felix
Felix

Reputation: 820

I had the exact same issue and solved it by moving the registration call into

applicationWillFinishLaunching(_ notification: Notification) 

Upvotes: 1

Michael Dautermann
Michael Dautermann

Reputation: 89509

You're almost there!

Looking at a tutorial article you might be looking at at, you still need to implement a method for handling the "kAEGetURL" Apple Event.

In your Application Delegate, create a method that looks like this:

func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {
    if let aeEventDescriptor = event?.paramDescriptorForKeyword(AEKeyword(keyDirectObject)) {
        if let urlStr = aeEventDescriptor.stringValue {
            let url = NSURL(string: urlStr)

            // do something with the URL
        }
    }
}

Upvotes: 0

Related Questions