How can I open my Swift app with url and pass data?

I am trying to get my application to catch the url that launched it and parse the values ​​passed in.

This is how it is done in ObjC

- (void)handleGetURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
  [event paramDescriptorForKeyword:keyDirectObject] ;

   NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
     // Now you can parse the URL and perform whatever action is needed
   NSLog(@"URL: %@", urlStr);
}

      

What I still know.

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

}

      

+3


source to share


2 answers


After days of cleaning the internet ... I found this solution.

func applicationWillFinishLaunching(notification: NSNotification?) {

    // -- launch the app with url
    NSAppleEventManager.sharedAppleEventManager().setEventHandler(self, andSelector: Selector("handleGetURLEvent:withReplyEvent:"), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}

func handleGetURLEvent(event: NSAppleEventDescriptor!, withReplyEvent: NSAppleEventDescriptor!) {
    let urlPassed = NSURL(string: event.paramDescriptorForKeyword(AEKeyword(keyDirectObject))!.stringValue!)
    println(urlPassed)
}

      



I had 2 questions in my code. First, my selector didn't match the function name to get the url (handleGetURLEvent). The second problem was finding the correct placement of exclamation marks for expanding options.

Hope this helps you if you have the same problem.

+3


source


I think this is what you need



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

      

+2


source







All Articles