sirikit

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SiriKit Development Skill

SiriKit开发技能

Empower users to interact with your app through voice, Shortcuts, and intelligent suggestions.
让用户能够通过语音、Shortcuts和智能建议与你的应用进行交互。

Quick Start

快速开始

Add Intents Extension

添加Intents扩展

  1. File → New → Target → Intents Extension
  2. Enable "Include UI Extension" if customizing Siri interface
  3. Enable Siri capability in main app target (Signing & Capabilities)
  1. 文件 → 新建 → 目标 → Intents Extension
  2. 如果要自定义Siri界面,请启用「Include UI Extension」
  3. 在主应用目标的「签名与功能」中启用Siri功能

Minimal Intent Handler

最简意图处理器

swift
import Intents

class IntentHandler: INExtension {
    override func handler(for intent: INIntent) -> Any {
        switch intent {
        case is OrderSoupIntent:
            return OrderSoupIntentHandler()
        default:
            return self
        }
    }
}

class OrderSoupIntentHandler: NSObject, OrderSoupIntentHandling {
    // 1. Resolve parameters
    func resolveSoup(for intent: OrderSoupIntent) async -> SoupResolutionResult {
        guard let soup = intent.soup else {
            return .needsValue()
        }
        return .success(with: soup)
    }
    
    // 2. Confirm intent
    func confirm(intent: OrderSoupIntent) async -> OrderSoupIntentResponse {
        return OrderSoupIntentResponse(code: .ready, userActivity: nil)
    }
    
    // 3. Handle intent
    func handle(intent: OrderSoupIntent) async -> OrderSoupIntentResponse {
        // Fulfill the request
        return OrderSoupIntentResponse.success(message: "Your order is confirmed!")
    }
}
swift
import Intents

class IntentHandler: INExtension {
    override func handler(for intent: INIntent) -> Any {
        switch intent {
        case is OrderSoupIntent:
            return OrderSoupIntentHandler()
        default:
            return self
        }
    }
}

class OrderSoupIntentHandler: NSObject, OrderSoupIntentHandling {
    // 1. Resolve parameters
    func resolveSoup(for intent: OrderSoupIntent) async -> SoupResolutionResult {
        guard let soup = intent.soup else {
            return .needsValue()
        }
        return .success(with: soup)
    }
    
    // 2. Confirm intent
    func confirm(intent: OrderSoupIntent) async -> OrderSoupIntentResponse {
        return OrderSoupIntentResponse(code: .ready, userActivity: nil)
    }
    
    // 3. Handle intent
    func handle(intent: OrderSoupIntent) async -> OrderSoupIntentResponse {
        // Fulfill the request
        return OrderSoupIntentResponse.success(message: "Your order is confirmed!")
    }
}

Intent Handling Flow

意图处理流程

┌─────────────────────────────────────────────────────────────┐
│                    User speaks to Siri                       │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 1. RESOLVE - Validate each parameter                         │
│    • Return .success(with:) if valid                        │
│    • Return .needsValue() if missing                        │
│    • Return .disambiguation(with:) for choices              │
│    • Return .unsupported() if invalid                       │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 2. CONFIRM - Final validation before execution               │
│    • Verify services are ready                              │
│    • Return .ready or appropriate failure code              │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 3. HANDLE - Fulfill the intent                               │
│    • Execute the action                                     │
│    • Return success/failure response                        │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│                    用户与Siri对话                            │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 1. 解析 - 验证每个参数                                        │
│    • 若有效则返回.success(with:)                           │
│    • 若缺失则返回.needsValue()                             │
│    • 若有多个选项则返回.disambiguation(with:)              │
│    • 若无效则返回.unsupported()                            │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 2. 确认 - 执行前的最终验证                                    │
│    • 验证服务是否就绪                                        │
│    • 返回.ready或相应的失败码                                │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 3. 处理 - 完成意图请求                                        │
│    • 执行对应操作                                            │
│    • 返回成功/失败响应                                        │
└─────────────────────────────────────────────────────────────┘

System Intent Domains

系统意图领域

DomainUse CasesKey Intents
MessagingSend/search messages
INSendMessageIntent
,
INSearchForMessagesIntent
CallingVoIP calls
INStartCallIntent
,
INSearchCallHistoryIntent
PaymentsMoney transfers
INSendPaymentIntent
,
INRequestPaymentIntent
Ride BookingRequest rides
INRequestRideIntent
,
INGetRideStatusIntent
WorkoutsStart/end workouts
INStartWorkoutIntent
,
INEndWorkoutIntent
MediaPlay audio/video
INPlayMediaIntent
,
INAddMediaIntent
PhotosSearch photos
INSearchForPhotosIntent
Lists & NotesCreate notes/tasks
INCreateNoteIntent
,
INAddTasksIntent
Car CommandsVehicle controls
INSetCarLockStatusIntent
,
INActivateCarSignalIntent
ReservationsRestaurant bookings
INGetReservationDetailsIntent
领域适用场景核心意图
消息发送/搜索消息
INSendMessageIntent
,
INSearchForMessagesIntent
通话VoIP通话
INStartCallIntent
,
INSearchCallHistoryIntent
支付转账
INSendPaymentIntent
,
INRequestPaymentIntent
打车叫车
INRequestRideIntent
,
INGetRideStatusIntent
健身开始/结束健身
INStartWorkoutIntent
,
INEndWorkoutIntent
媒体播放音视频
INPlayMediaIntent
,
INAddMediaIntent
照片搜索照片
INSearchForPhotosIntent
列表与笔记创建笔记/任务
INCreateNoteIntent
,
INAddTasksIntent
车载指令车辆控制
INSetCarLockStatusIntent
,
INActivateCarSignalIntent
预订餐厅预订
INGetReservationDetailsIntent

Custom Intents

自定义意图

Define in Intent Definition File

在意图定义文件中定义

  1. Create
    Intents.intentdefinition
    file
  2. Add new intent with VerbNoun naming (e.g.,
    OrderSoup
    )
  3. Set category matching purpose
  4. Define parameters with types
  1. 创建
    Intents.intentdefinition
    文件
  2. 添加新意图,采用「动词+名词」命名方式(例如
    OrderSoup
  3. 设置与用途匹配的分类
  4. 定义带类型的参数

Parameter Types

参数类型

  • System: String, Integer, Boolean, Date, Person, Location, Currency
  • Custom: Define your own types as enums or objects
  • 系统类型:字符串、整数、布尔值、日期、人物、位置、货币
  • 自定义类型:将你自己的类型定义为枚举或对象

Reference Documentation

参考文档

  • Intent Handling: Resolution, confirmation, handling patterns
  • Shortcuts: Donating, suggesting, and managing shortcuts
  • Custom Intents: Intent definition file, parameters, responses
  • IntentsUI: Custom Siri interface views
  • Vocabulary: Custom terminology and phrases
  • App Intents Migration: Modern App Intents framework
  • 意图处理: 解析、确认、处理模式
  • Shortcuts: 快捷指令的捐赠、推荐与管理
  • 自定义意图: 意图定义文件、参数、响应
  • IntentsUI: 自定义Siri界面视图
  • 词汇: 自定义术语与短语
  • App Intents迁移: 现代App Intents框架

Key Configuration

关键配置

Info.plist (Intents Extension)

Info.plist(Intents扩展)

xml
<key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>IntentsSupported</key>
        <array>
            <string>OrderSoupIntent</string>
        </array>
        <key>IntentsRestrictedWhileLocked</key>
        <array>
            <string>INSendPaymentIntent</string>
        </array>
    </dict>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.intents-service</string>
    <key>NSExtensionPrincipalClass</key>
    <string>$(PRODUCT_MODULE_NAME).IntentHandler</string>
</dict>
xml
<key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>IntentsSupported</key>
        <array>
            <string>OrderSoupIntent</string>
        </array>
        <key>IntentsRestrictedWhileLocked</key>
        <array>
            <string>INSendPaymentIntent</string>
        </array>
    </dict>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.intents-service</string>
    <key>NSExtensionPrincipalClass</key>
    <string>$(PRODUCT_MODULE_NAME).IntentHandler</string>
</dict>

Request Siri Authorization

请求Siri授权

swift
import Intents

INPreferences.requestSiriAuthorization { status in
    switch status {
    case .authorized: print("Siri authorized")
    case .denied: print("Siri denied")
    case .notDetermined: print("Not determined")
    case .restricted: print("Restricted")
    @unknown default: break
    }
}
swift
import Intents

INPreferences.requestSiriAuthorization { status in
    switch status {
    case .authorized: print("Siri authorized")
    case .denied: print("Siri denied")
    case .notDetermined: print("Not determined")
    case .restricted: print("Restricted")
    @unknown default: break
    }
}

Common Patterns

常见模式

Donate Shortcut After User Action

用户操作后捐赠快捷指令

swift
import Intents

func donateOrderShortcut(order: Order) {
    let intent = OrderSoupIntent()
    intent.soup = order.soup
    intent.quantity = order.quantity
    
    let interaction = INInteraction(intent: intent, response: nil)
    interaction.identifier = order.id.uuidString
    
    interaction.donate { error in
        if let error = error {
            print("Donation failed: \(error)")
        }
    }
}
swift
import Intents

func donateOrderShortcut(order: Order) {
    let intent = OrderSoupIntent()
    intent.soup = order.soup
    intent.quantity = order.quantity
    
    let interaction = INInteraction(intent: intent, response: nil)
    interaction.identifier = order.id.uuidString
    
    interaction.donate { error in
        if let error = error {
            print("Donation failed: \(error)")
        }
    }
}

Delete Donated Shortcuts

删除已捐赠的快捷指令

swift
// Delete specific
INInteraction.delete(with: [orderID.uuidString]) { error in }

// Delete all from app
INInteraction.deleteAll { error in }
swift
// 删除指定快捷指令
INInteraction.delete(with: [orderID.uuidString]) { error in }

// 删除应用的所有捐赠快捷指令
INInteraction.deleteAll { error in }

Handle Intent in App (when launched)

在应用中处理意图(启动时)

swift
// SwiftUI
.onContinueUserActivity(NSStringFromClass(OrderSoupIntent.self)) { activity in
    if let intent = activity.interaction?.intent as? OrderSoupIntent {
        handleOrderIntent(intent)
    }
}

// UIKit SceneDelegate
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
    if let intent = userActivity.interaction?.intent as? OrderSoupIntent {
        handleOrderIntent(intent)
    }
}
swift
// SwiftUI
.onContinueUserActivity(NSStringFromClass(OrderSoupIntent.self)) { activity in
    if let intent = activity.interaction?.intent as? OrderSoupIntent {
        handleOrderIntent(intent)
    }
}

// UIKit SceneDelegate
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
    if let intent = userActivity.interaction?.intent as? OrderSoupIntent {
        handleOrderIntent(intent)
    }
}

Key Constraints

关键限制

  • Background execution: Extensions run briefly; launch app for long tasks
  • Shared data: Use App Groups for data between app and extension
  • No UI in extension: Use IntentsUI extension for custom views
  • Testing: Wait after install for Siri to recognize new intents
  • Localization: Provide localized
    AppIntentVocabulary.plist
  • 后台执行:扩展运行时间有限;长时间任务需启动主应用
  • 共享数据:使用App Groups在应用与扩展之间共享数据
  • 扩展中无UI:使用IntentsUI扩展创建自定义视图
  • 测试:安装后需等待一段时间,Siri才能识别新意图
  • 本地化:提供本地化的
    AppIntentVocabulary.plist
    文件