基于AppIntents的.system.search意图歧义消除条目列表实现问询
基于AppIntents的.system.search意图歧义消除条目列表实现问询
嘿,我来帮你搞定基于AppIntents的.system.search意图歧义消除列表的实现~ 先看你已经写了一部分的TrailSearch.swift,接下来咱们把它补全并梳理清楚关键步骤:
第一步:定义Trail数据模型(如果还未实现)
首先需要一个模拟的步道数据源,用来提供歧义消除的候选条目:
struct Trail: Identifiable { let id: String let name: String let location: String } // 模拟的步道数据集,实际项目可替换为真实数据源 extension Trail { static let sampleTrails = [ Trail(id: "1", name: "Mountain View Trail", location: "California"), Trail(id: "2", name: "Forest Loop Trail", location: "Oregon"), Trail(id: "3", name: "Coastal Path Trail", location: "Washington") ] }
第二步:完善TrailSearch Intent
核心是通过实现参数的resolve方法返回候选条目,触发系统的歧义消除选择流程:
import AppIntents @available(iOS 18.0, *) @AssistantIntent(schema: .system.search) struct TrailSearch: AppIntent { static let title: LocalizedStringResource = "Search Trail" // 添加搜索关键词参数,作为触发歧义消除的核心载体 @Parameter(title: "Trail Name") var trailName: String? // 实现参数的resolve方法,处理歧义逻辑 func resolveTrailName() async throws -> ResolveResult<String> { guard let query = trailName, !query.isEmpty else { // 用户未输入关键词时,返回所有步道候选 let candidates = Trail.sampleTrails.map { IntentItem($0.name, id: $0.id) } return .needsValue(candidates: candidates) } // 根据关键词过滤匹配的步道 let filteredTrails = Trail.sampleTrails.filter { $0.name.localizedCaseInsensitiveContains(query) } switch filteredTrails.count { case 0: // 无匹配结果,返回提示 return .unsupported("No trails found matching '\(query)'") case 1: // 唯一匹配,直接确认使用该结果 return .success(with: filteredTrails[0].name) default: // 多结果匹配,返回候选列表(可添加副标题增强辨识度) let candidates = filteredTrails.map { IntentItem($0.name, id: $0.id, subtitle: $0.location) } return .needsValue(candidates: candidates) } } // 执行Intent的实际逻辑,比如展示步道详情 func perform() async throws -> some IntentResult { guard let trailName = trailName else { return .result(dialog: "Please specify a trail name.") } let matchedTrail = Trail.sampleTrails.first { $0.name.localizedCaseInsensitiveContains(trailName) } if let trail = matchedTrail { return .result(dialog: "Showing details for \(trail.name) in \(trail.location)") } else { return .result(dialog: "Couldn't find that trail.") } } }
关键逻辑说明
@AssistantIntent(schema: .system.search):这个标记让你的Intent归属于系统搜索Schema,确保Siri或系统搜索入口能识别并触发它。resolveTrailName方法:这是歧义消除的核心——当搜索词匹配多个结果时,返回.needsValue(candidates:),系统会自动弹出候选列表让用户选择;唯一匹配则直接确认,无匹配则提示用户。IntentItem:可自定义候选条目的标题、ID和副标题,帮助用户清晰区分不同选项。
注意事项
- 确保项目部署目标为iOS 18.0及以上,因为
@AssistantIntent和.system.search是iOS 18新增API。 - 如果数据源来自网络,需在
resolve方法中处理异步加载逻辑,保证候选列表正确展示。 - 可根据需求调整
resolve逻辑,比如支持按位置、难度等多维度过滤候选。
备注:内容来源于stack exchange,提问作者Ortwin Gentz
相关产品推荐
相关产品推荐

