【问题标题】:How to capture the URL used to launch an OS X application via URLScheme in Swift?如何在 Swift 中通过 URLScheme 捕获用于启动 OS X 应用程序的 URL?
【发布时间】:2014-06-06 10:58:51
【问题描述】:

我一直在尝试在 Swift 中复制 Objective-C 中执行此操作的常用方法,用于我正在玩的一个新的 swift 应用程序。

如何在 Objective-C 中执行此操作已有详细记录,您获取共享的 Apple 事件管理器并调用 setEventHandler 方法将函数注册为事件类 kInternetEventClass 的处理程序,事件 ID 为 kAEGetURL

因此,在 swift 中,我试图在一个全新的项目中使用添加到模板 AppDelegate.swift 中的这段代码来做同样的事情:

func applicationWillFinishLaunching(aNotification: NSNotification?) {
    var appleEventManager:NSAppleEventManager = NSAppleEventManager.sharedAppleEventManager()
    appleEventManager.setEventHandler(self, andSelector: "handleGetURLEvent:withReplyEvent:", forEventClass: kInternetEventClass, andEventID: kAEGetURL)
}

func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {
    println("yay");
}

据我所知,这只是标准 Objective-c 调用的语法转换。但是对于 setEventHandler 方法的 forEventClassandEventId 参数,我都遇到了类型错误:

'NSNumber' is not a subtype of 'AEEventClass' 用于 forEventClass 参数

和:

'NSNumber' is not a subtype of 'AEEventId' 用于 andEventID 参数

我不确定我在这个阶段做错了什么,因为kInternetEventClasskAEGetURL 都是苹果定义的常量...当然我不需要将它们的NSNumber 类型转换为它们各自的类型需要的类型?如果我是,我不知道怎么做。

【问题讨论】:

    标签: macos swift xcode6


    【解决方案1】:

    据我从文档中可以看出,类采用常量并将其转换为正确的类型:

    func applicationWillFinishLaunching(aNotification: NSNotification?) {
        var appleEventManager:NSAppleEventManager = NSAppleEventManager.sharedAppleEventManager()
        appleEventManager.setEventHandler(self, andSelector: "handleGetURLEvent:withReplyEvent:", forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
    }
    

    【讨论】:

    • 如果有人真的知道这里发生了什么以及正确的术语是什么,请编辑我的答案。谢谢!
    • 是的,谢谢,这似乎行得通 - 虽然这是必需的,但感觉很奇怪。
    • 值得一提的是,您的选择器字符串应该是“handleGetURLEvent:replyEvent:”以正确匹配上面的 Swift func 声明。
    【解决方案2】:

    我发现从 Xcode 8.2 开始,我需要将 MagerValp 的代码转换为以下代码:

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

    希望这会有所帮助。

    【讨论】:

    • 当我尝试通过自定义 url 打开我的应用程序时,console.app 中出现错误:-[MyApp.AppDelegate handleGetURLEvent:withReplyEvent:]: unrecognized selector sent to instance 0x60c0000039b0(我已将 handleGetURLEvent 中的第二个参数命名为 withReplyEvent)。任何的想法?使用 Xcode 8.3.3 (8E3004b)
    • 解决我的问题stackoverflow.com/questions/46065842/…,将Selector(("handleGetURLEvent:withReplyEvent:")) 替换为新的样式选择器:#selector(AppDelegate.handleGetURLEvent(event:replyEvent:))
    猜你喜欢
    • 1970-01-01
    • 2017-07-29
    • 2016-08-23
    • 2012-04-01
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多