WWDC21: 组件智能化 Add intelligence to your widgets
发布
更新
字数
558
阅读
3 分钟
阅读量
849
新的 Smart Rotate、Widget Suggestions 特性,可以让智能堆叠内的小组件根据优先级、时效自动排序。
Smart Rotate | Widget Suggestions | Adoption Site | |
---|---|---|---|
INRelevantShortcut |
✅ | App | |
TimelineEntryRelevance |
✅ | Widget extension | |
INInteraction |
✅ | ✅ | App |
INRelevantShortCut
for Widget Suggestions
- App 内通知系统,把 widget 插入智能堆叠
- 指定基于时间或行为的相关性
- 支持 static 和 intent-configured widgets
// Donate INRelevantShortcut for Widget Suggestions in app
// User has just made a purchase
// 5. Set the array of relevant shortcuts in the default store
var relevantShortcuts: [INRelevantShortcut] = []
// 1. Create the intent and set necessary parameters
let intent = ViewRecentPurchasesIntent()
intent.card = Card(identifier: card.identifier)
intent.category = .all
if let shortcut = INShortcut(intent: intent) {
// 2. Create an `InRelevantShortcut` with the intent
let relevantShortcut = INRelevantShortcut(shortcut: shortcut)
// 3. Set the widget kind
relevantShortcut.shortcutRole = .information
relevantShortcut.widgetKind = “CardRecentPurchasesWidget”
// 4. Set array of `INRelevanceProvider`
let dateProvider = INDateRelevanceProvider(start: Date(),
end: Date(timeIntervalSinceNow: 1800))
relevantShortcut.relevanceProviders = [dateProvider]
relevantShortcuts.append(relevantShortcut)
}
// 6. Update donated relevant shortcust by donating a new array
INRelevantShortcutStore.default.setRelevantShortcuts(relevantShortcuts) { (error) in
if let error = error {
print("Failed to set relevant shortcuts. \(error))")
} else {
print("Relevant shortcuts set.")
}
}
使用 INDateRelevanceProvider
设置时间相关的优先级,如果不设置 providers
系统则默认根据行为相关性排序。
TimelineEntryRelevance
for Smart Rotate
在 Widget 内为 timeline entry 设置相关性,TimelineEntry
协议有两个属性 var date: Date?
和 var relevance: TimelineEntryRelevance?
relevance
可以设置 score
Float
类型和 duration
TimeInterval
类型:Score 用来打分,允许负值,不允许为 0
,分值大小是相对的,应选择适当的取值范围,能够覆盖全部的 timeline entry;Duration 可以指定分值有效期,duration 结束后 score 会按 0 处理,如果 duration 为 0,score 将被使用直到下一个 entry 生效。
// Appending TimelineEntryRelevance to a TimelineEntry in widget extension for Smart Rotate
struct CardRecentPurchasesEntry: TimelineEntry {
let date: Date
let relevance: TimelineEntryRelevance?
let card: IntentCard?
let category: PurchaseCategory
}
let relevance = TimelineEntryRelevance(score: 16.29, duration: 1800)
let entry = CardRecentPurchasesEntry(date: Date(), relevance: relevance, card: card,
category: category)
INInteraction
to enable both Smart Rotate and Widget Suggestions
当用户发生交互时,可以为 Intent 打分(Donate),Intent 会被系统用作基于用户习惯的学习进行识别、分析。
// Donate INIntent in a card's purchases list in the app
.onAppear {
let intent = ViewRecentPurchasesIntent()
intent.card = Card(identifier: card.id.uuidString, displayString: card.name)
intent.category = .all
let interaction = INInteraction(intent: intent, response: nil)
interaction.donate { error in
if let error = error {
print(error.localizedDescription)
}
}
}