如何使用URL打开我的Swift应用程序并传递数据?

时间:2014-11-20 16:58:14

标签: objective-c cocoa url swift uri

我正在尝试让我的应用能够捕获启动它的网址,并解析传递的值。

以下是在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);
}

到目前为止我所拥有的是......

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

}

2 个答案:

答案 0 :(得分:3)

经过几天的网络搜索......我找到了这个解决方案。

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)
}

我的代码中有2个问题。首先,我的选择器与获取url(handleGetURLEvent)的函数名称不匹配。第二个问题是找到正确放置感叹号以展开选项。

希望如果您遇到同样的问题,这会帮助您解决问题。

答案 1 :(得分:2)

我认为这就是你需要的

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