我对Swift 的意图非常陌生.使用来自WWDC 22的Dive Into App Intents个视频和Booky个示例应用程序,我已经让我的应用程序显示在快捷方式应用程序中,并显示一个初始快捷方式,该快捷方式可以打开应用程序的主视图.下面是AppIntents
代码:
import AppIntents
enum NavigationType: String, AppEnum, CaseDisplayRepresentable {
case folders
case cards
case favorites
// This will be displayed as the title of the menu shown when picking from the options
static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Navigation")
static var caseDisplayRepresentations: [Self:DisplayRepresentation] = [
.folders: DisplayRepresentation(title: "Folders"),
.cards: DisplayRepresentation(title: "Card Gallery"),
.favorites: DisplayRepresentation(title: "Favorites")
]
}
struct OpenCards: AppIntent {
// Title of the action in the Shortcuts app
static var title: LocalizedStringResource = "Open Card Gallery"
// Description of the action in the Shortcuts app
static var description: IntentDescription = IntentDescription("This action will open the Card gallery in the Hello There app.", categoryName: "Navigation")
// This opens the host app when the action is run
static var openAppWhenRun = true
@Parameter(title: "Navigation")
var navigation: NavigationType
@MainActor // <-- include if the code needs to be run on the main thread
func perform() async throws -> some IntentResult {
ViewModel.shared.navigateToGallery()
return .result()
}
static var parameterSummary: some ParameterSummary {
Summary("Open \(\.$navigation)")
}
}
这里是ViewModel:
import SwiftUI
class ViewModel: ObservableObject {
static let shared = ViewModel()
@Published var path: any View = FavoritesView()
// Clears the navigation stack and returns home
func navigateToGallery() {
path = FavoritesView()
}
}
现在,快捷方式可以让你 Select 一个枚举(文件夹、卡片和Collection 夹),但总是启动到应用程序的根目录.基本上没有什么不同,只是告诉Siri打开我的应用程序.我的应用程序在其内容视图中使用TabView
,相关视图使用TabItems:
.tabItem {
Text("Folders")
Image(systemName: "folder.fill")
}
NavigationView {
GalleryView()
}
.tabItem {
Text("Cards")
Image(systemName: "rectangle.portrait.on.rectangle.portrait.angled.fill")
}
NavigationView {
FavoritesView()
}
.tabItem {
Text("Favs")
Image(systemName: "star.square.on.square.fill")
}
NavigationView {
SettingsView()
}
.tabItem {
Text("Settings")
Image(systemName: "gear")
}
如何将上面的AppIntents配置为包含类似于"Open Favorites View"的内容,并将其启动到该TabItem视图中?我认为ViewModel
需要调整一下...我试图将其配置为默认打开FavoritesView()
,但我在前进的正确道路上迷路了.
谢谢!
[编辑--使用当前代码更新]