通过 URL Scheme 打开 Cocoa App

wet*_*osh 0 macos cocoa swift

我的问题与这个问题相同,但它已经有一段时间没有更新了,而且自从被问到 Swift 已经发生了很大的变化,所以答案可能需要刷新。我想要做的就是捕获用于打开我的可可应用程序的 url,但代码永远不会在我的处理程序函数中执行。当我通过自定义 url 方案启动我的应用程序时,在 Console.app 中抛出错误。以下是错误:

-[MyApp.AppDelegate handleGetURLEvent:replyEvent:]: unrecognized selector sent to instance 0x60c0000039b0
-[MyApp.AppDelegate handleGetURLEvent:replyEvent:]: unrecognized selector sent to instance 0x60c0000039b0
    OSErr AERemoveEventHandler(AEEventClass, AEEventID, AEEventHandlerUPP, Boolean)(spec,phac handler=0x7fff576b7f15 isSys=YES) err=0/noErr
-[MyApp.AppDelegate handleGetURLEvent:replyEvent:]: unrecognized selector sent to instance 0x60c0000039b0
-[MyApp.AppDelegate handleGetURLEvent:replyEvent:]: unrecognized selector sent to instance 0x60c0000039b0
    OSErr AERemoveEventHandler(AEEventClass, AEEventID, AEEventHandlerUPP, Boolean)(GURL,GURL handler=0x7fff5661d680 isSys=YES) err=0/noErr
LSExceptions shared instance invalidated for timeout.
Run Code Online (Sandbox Code Playgroud)

而我的裸骨应用程序:

创建一个名为 MyApp 的新 Cocoa 应用程序。在 Info > URL Types 中,在 Identifier 字段和blue(例如)URL Schemes 字段中输入我的应用程序的包标识符。将以下两个函数添加到 AppDelegate 类中:

func applicationWillFinishLaunching(_ notification: Notification) {
    let appleEventManager: NSAppleEventManager = NSAppleEventManager.shared()
    appleEventManager.setEventHandler(self, andSelector: Selector(("handleGetURLEvent:replyEvent:")), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}

func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {
    NSLog("heyo!")
}
Run Code Online (Sandbox Code Playgroud)

构建并运行我的应用程序。退出它,然后在 Safariblue://whatever中在地址栏中输入并点击返回。应用程序打开,但 NSLog 没有显示在 Console.app 中,而是出现了我上面提到的错误。我很想被困在如何解析 url 上,但我什至无法进入那部分。我正在运行 Xcode 8.3.3 (8E3004b) 和 Swift 3.1。大家得到的结果和我一样吗?我是否错误地调用了处理程序函数?

UKD*_*eek 5

@Lucas Derraugh 是个天才 - 我到处寻找那个解决方案。谢谢!

Swift 4 Xcode 上的一个添加提示我将 @objc 添加到函数中,所以我有:

  func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Register for Call back URL events
        let aem = NSAppleEventManager.shared();
        aem.setEventHandler(self, andSelector: #selector(AppDelegate.handleGetURLEvent(event:replyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))

    }

  @objc func handleGetURLEvent(event: NSAppleEventDescriptor, replyEvent: NSAppleEventDescriptor) {

    let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue!
        let url = URL(string: urlString!)!
       // DO what you will you now have a url.. 

    }
Run Code Online (Sandbox Code Playgroud)