2017-09-06 55 views
0

我的问题是相同的this question但它已经有一段时间没有更新和斯威夫特已经改变了很多,因为有人问这样的答案可能需要刷新。我想要做的就是捕获用于打开我的可可应用程序的URL,但代码从未在我的处理函数中执行。当我通过自定义url方案启动我的应用程序时,Console.app中会引发错误。下面是错误的:打开可可应用程序通过URL方案

-[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. 

而且我裸露的骨头应用:

创建名为MyApp一个新的Cocoa程序。在信息> URL类型,在标识符字段中输入我的应用程序的包标识,并在URL方案领域blue(例如)。将以下两个函数添加到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!") 
} 

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

回答

2

尝试#selector(AppDelegate.handleGetURLEvent(event:replyEvent:))换出Selector(("handleGetURLEvent:replyEvent:"))#selector宏将在编译时验证该方法的存在,因此应该在运行时使用正确的选择器。

顺便

-[MyApp.AppDelegate handleGetURLEvent:replyEvent:]: unrecognized selector sent to instance 0x60c0000039b0 

是说handleGetURLEvent:replyEvent:叫上AppDelegate中,但它并没有对此消息作出回应,这意味着要么选择被拼写错误或者被送到了错误的对象。在这种情况下,可能是被拼错的情况,因为该Selector()语法对象 - 所以这是很难知道的当量是斯威夫特的东西。这就是为什么你应该使用#selector

+0

你是正确的精先生!我将在我引用的问题上留下你的解决方案的评论。万分感谢! – wetjosh

0

@Lucas Derraugh是个天才 - 我找遍了该解决方案。谢谢!

另外一个斯威夫特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.. 

    } 
相关问题