如何在應(yīng)用中集成 SiriKit

要在應(yīng)用中集成 SiriKit,首先需要在 Xcode 中創(chuàng)建一個(gè)新的 Intents Extension。這個(gè)擴(kuò)展將處理所有與 Siri 的交互請(qǐng)求。開(kāi)發(fā)者需要在擴(kuò)展中實(shí)現(xiàn)特定的協(xié)議,以響應(yīng)用戶(hù)通過(guò) Siri 發(fā)出的請(qǐng)求。

創(chuàng)建 Intents Extension

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

Intents Extension

使用 SiriKit 發(fā)送消息的實(shí)現(xiàn)

在 SiriKit 中發(fā)送消息是一個(gè)常見(jiàn)的功能。以下是實(shí)現(xiàn)這一功能的步驟。

創(chuàng)建項(xiàng)目和配置

首先,在 Xcode 中創(chuàng)建一個(gè)新的項(xiàng)目,并添加一個(gè) Intents Extension。然后,在 Info.plist 文件中配置支持的意圖,例如 INSendMessageIntent。確保應(yīng)用有權(quán)訪(fǎng)問(wèn)用戶(hù)的聯(lián)系人信息,以便正確解析和發(fā)送消息。

共享的用戶(hù)信息

在主項(xiàng)目中創(chuàng)建一個(gè) MyAccount.swift 文件,用于管理用戶(hù)信息和消息發(fā)送邏輯。以下是示例代碼:

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("模擬發(fā)送消息:(message) 給 (recipients)")
        return .success
    }
}

處理 Siri 數(shù)據(jù)

IntentHandler.swift 中,蘋(píng)果已經(jīng)為我們生成了消息的示例代碼。開(kāi)發(fā)者只需實(shí)現(xiàn) INSendMessageIntentHandling 協(xié)議中的方法來(lái)處理和發(fā)送消息。

實(shí)現(xiàn)步驟

  1. Resolve:解析 Siri 數(shù)據(jù),處理收件人和發(fā)送內(nèi)容。
  2. Confirm:確認(rèn)階段,判斷用戶(hù)權(quán)限和獲取 intent 事件中的值。
  3. Handle:處理階段,實(shí)現(xiàn)應(yīng)用消息發(fā)送的邏輯。

以下是 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()])
        }
    }

    // 處理發(fā)送的文字內(nèi)容
    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).
    // 確認(rèn)階段,可以判斷用戶(hù)是否有權(quán)限(如是否已登錄)、可以獲取intent事件中的值,并可對(duì)其做最終修改
    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).
    // 處理階段,實(shí)現(xiàn)app消息發(fā)送的代碼邏輯
    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)
        }
    }
}

實(shí)現(xiàn) Siri Shortcuts

Siri Shortcuts 是蘋(píng)果在 iOS12 推出的新功能,允許用戶(hù)通過(guò)自定義的短語(yǔ)執(zhí)行特定的操作。開(kāi)發(fā)者可以使用 Siri Shortcuts 來(lái)簡(jiǎn)化用戶(hù)的操作流程。例如,用戶(hù)可以設(shè)置短語(yǔ)“播放下雨聲”來(lái)觸發(fā)某個(gè)應(yīng)用的白噪音播放功能。

Siri Shortcuts

FAQ

問(wèn):如何在應(yīng)用中啟用 SiriKit?

問(wèn):SiriKit 支持哪些功能?

問(wèn):如何測(cè)試 SiriKit 的功能?

問(wèn):什么是 Siri Shortcuts?

問(wèn):如何確保應(yīng)用的 SiriKit 集成順利?

上一篇:

Java 調(diào)用 WaveNet API 實(shí)現(xiàn)語(yǔ)音合成

下一篇:

Polly調(diào)查問(wèn)卷API快速集成的使用案例
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門(mén)場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)