无法在 Swift 2.3 中编译 Siri 扩展

Unable to compile Siri extension in Swift 2.3

我想在我的应用程序中集成 Siri/Intent 扩展,目前基于 Swift 2.3。我正在使用 Xcode 8 beta 6 版本。

该应用甚至无法编译,并给出错误


Type 'IntentHandler' does not conform to protocol 'INSendMessageIntentHandling'

Protocol requires function 'handle(sendMessage:completion:)' with type '(sendMessage: INSendMessageIntent, completion: (INSendMessageIntentResponse) -> Void) -> Void'

Objective-C method 'handleWithSendMessage:completion:' provided by method 'handle(sendMessage:completion:)' does not match the requirement's selector ('handleSendMessage:completion:')


即使是 Apple 的示例应用程序,UnicornChat 也无法编译并出现相同的错误。我确实将 SWIFT_VERSION 标志更改为 Yes,以支持 Swift 2.3

示例代码:

func handle(sendMessage intent: INSendMessageIntent, completion: (INSendMessageIntentResponse) -> Void) {
        let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self))
        let response = INSendMessageIntentResponse(code: .Success, userActivity: userActivity)
        completion(response)
    }

失败并出现上述错误。

有人知道如何让 Siri 在 Swift 2.3 中工作吗?

显然 Xcode 8 beta 6 已经更新到 Swift 3 并且回调需要在方法中添加 @escaping:

func handle(sendMessage intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Swift.Void) {  
  //..  
}

如果 Siri 委托方法已更新为 Swift 3(似乎是这种情况),那么恐怕您也必须使用 Swift 3,或更旧的版本SDK。

所以,这有帮助

https://forums.developer.apple.com/message/174455#174455

我们需要使用 Swift 显式定义 @objc 方法签名。如以下作品。

@objc (handleSendMessage:completion:)
func handle(sendMessage intent: INSendMessageIntent, completion: (INSendMessageIntentResponse) -> Void) {
 //..
}

使用 Swift 2.3 编译代码时,需要将 Use Legacy Swift Language Version 设置为 YES 用于 Siri 和 SiriUI 目标。

此外,当创建 IntentHandlerIntentViewController 时,方法可能已在 Swift 3 中创建(恰好我)。因此,将 类 转换为 Swift 2.3,并使用 @objc 方法签名和委托。

对于IntentHandler,

@objc (handleSendMessage:completion:)
func handle(sendMessage intent: INSendMessageIntent, completion: (INSendMessageIntentResponse) -> Void) {
}

@objc (handleSearchForMessages:completion:)
func handle(searchForMessages intent: INSearchForMessagesIntent, completion: (INSearchForMessagesIntentResponse) -> Void) {
}

@objc (handleSetMessageAttribute:completion:)
func handle(setMessageAttribute intent: INSetMessageAttributeIntent, completion: (INSetMessageAttributeIntentResponse) -> Void) {
}

对于IntentViewController,

@objc (configureWithInteraction:context:completion:)
func configureWithInteraction(interaction: INInteraction!, context: INUIHostedViewContext, completion: ((CGSize) -> Void)!) {
}

希望对您有所帮助。