如何在應用中集成 SiriKit

要在應用中集成 SiriKit,首先需要在 Xcode 中創建一個新的 Intents Extension。這個擴展將處理所有與 Siri 的交互請求。開發者需要在擴展中實現特定的協議,以響應用戶通過 Siri 發出的請求。

創建 Intents Extension

在 Xcode 中,選擇 File -> New -> Target,然后選擇 Intents Extension。命名為 MySiriExtension,并勾選 Include UI Extension,以便后續添加交互界面。

Intents Extension

使用 SiriKit 發送消息的實現

在 SiriKit 中發送消息是一個常見的功能。以下是實現這一功能的步驟。

創建項目和配置

首先,在 Xcode 中創建一個新的項目,并添加一個 Intents Extension。然后,在 Info.plist 文件中配置支持的意圖,例如 INSendMessageIntent。確保應用有權訪問用戶的聯系人信息,以便正確解析和發送消息。

共享的用戶信息

在主項目中創建一個 MyAccount.swift 文件,用于管理用戶信息和消息發送邏輯。以下是示例代碼:

import Intents

class MyUser {
    var name: String?
    var handle: String?

    init(name: String? = nil, handle: String? = nil) {
        self.name = name
        self.handle = handle
    }

    func toInPerson() -> INPerson {
        return INPerson(handle: handle!, displayName: name, contactIdentifier: name)
    }
}

class MyAccount {
    private static let instance = MyAccount()

    class func share() -> MyAccount {
        return MyAccount.instance
    }

    func contact(matchingName: String) -> [MyUser] {
        return [MyUser(name: matchingName, handle: NSStringFromClass(MySendMessageIntentHandler.classForCoder()))]
    }

    func send(message: String, to recipients: [INPerson]) -> INSendMessageIntentResponseCode {
        print("模擬發送消息:(message) 給 (recipients)")
        return .success
    }
}

處理 Siri 數據

IntentHandler.swift 中,蘋果已經為我們生成了消息的示例代碼。開發者只需實現 INSendMessageIntentHandling 協議中的方法來處理和發送消息。

實現步驟

  1. Resolve:解析 Siri 數據,處理收件人和發送內容。
  2. Confirm:確認階段,判斷用戶權限和獲取 intent 事件中的值。
  3. Handle:處理階段,實現應用消息發送的邏輯。

以下是 MySendMessageIntentHandler.swift 的示例代碼:

import UIKit
import Intents

class MySendMessageIntentHandler: NSObject, INSendMessageIntentHandling {
    // MARK: - INSendMessageIntentHandling

    // Implement resolution methods to provide additional information about your intent (optional).
    // 處理收件人
    func resolveRecipients(for intent: INSendMessageIntent, with completion: @escaping ([INSendMessageRecipientResolutionResult]) -> Void) {
        if let recipients = intent.recipients {
            // If no recipients were provided we'll need to prompt for a value.
            if recipients.count == 0 {
                completion([INSendMessageRecipientResolutionResult.needsValue()])
                return
            }

            var resolutionResults = [INSendMessageRecipientResolutionResult]()
            for recipient in recipients {
                let matchingContacts = MyAccount.share().contact(matchingName: recipient.displayName)
                // Implement your contact matching logic here to create an array of matching contacts
                switch matchingContacts.count {
                case 2  ... Int.max:
                    // We need Siri's help to ask user to pick one from the matches.
                    let disambiguations = matchingContacts.map{ $0.toInPerson() }
                    resolutionResults += [INSendMessageRecipientResolutionResult.disambiguation(with: disambiguations)]

                case 1:
                    // We have exactly one matching contact
                    let recipient = matchingContacts[0].toInPerson()
                    resolutionResults += [INSendMessageRecipientResolutionResult.success(with: recipient)]

                case 0:
                    // We have no contacts matching the description provided
                    resolutionResults += [INSendMessageRecipientResolutionResult.unsupported()]

                default:
                    break
                }
            }
            completion(resolutionResults)
        } else {
            completion([INSendMessageRecipientResolutionResult.needsValue()])
        }
    }

    // 處理發送的文字內容
    func resolveContent(for intent: INSendMessageIntent, with completion: @escaping (INStringResolutionResult) -> Void) {
        if let text = intent.content, !text.isEmpty {
            completion(INStringResolutionResult.success(with: text))
        } else {
            completion(INStringResolutionResult.needsValue())
        }
    }

    // Once resolution is completed, perform validation on the intent and provide confirmation (optional).
    // 確認階段,可以判斷用戶是否有權限(如是否已登錄)、可以獲取intent事件中的值,并可對其做最終修改
    func confirm(intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Void) {
        // Verify user is authenticated and your app is ready to send a message.

        let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self))
        let response = INSendMessageIntentResponse(code: .ready, userActivity: userActivity)
        completion(response)
    }

    // Handle the completed intent (required).
    // 處理階段,實現app消息發送的代碼邏輯
    func handle(intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Void) {
        // Implement your application logic to send a message here.
        if let content = intent.content, let recipients = intent.recipients {
            let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self))
            let sendResult = MyAccount.share().send(message: content, to: recipients)
            completion(INSendMessageIntentResponse(code: sendResult, userActivity: userActivity))
        } else {
            let response = INSendMessageIntentResponse(code: .failure, userActivity: nil)
            completion(response)
        }
    }
}

實現 Siri Shortcuts

Siri Shortcuts 是蘋果在 iOS12 推出的新功能,允許用戶通過自定義的短語執行特定的操作。開發者可以使用 Siri Shortcuts 來簡化用戶的操作流程。例如,用戶可以設置短語“播放下雨聲”來觸發某個應用的白噪音播放功能。

Siri Shortcuts

FAQ

問:如何在應用中啟用 SiriKit?

問:SiriKit 支持哪些功能?

問:如何測試 SiriKit 的功能?

問:什么是 Siri Shortcuts?

問:如何確保應用的 SiriKit 集成順利?

上一篇:

Java 調用 WaveNet API 實現語音合成

下一篇:

Polly調查問卷API快速集成的使用案例
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費