Я пытаюсь настроить ярлыки и AppIntents, чтобы позволить пользователю вызывать Siri и открывать диалоговое окно для создания новой записи с двумя или более атрибутами модели SwiftData. Я успешно написал код для Siri, чтобы открыть приложение, и для Siri, чтобы открыть приложение и перейти на страницу, чтобы добавить запись, но мне не удалось захватить ответ пользователя из приглашения Siri и сохранить его в новых записях. Если это описано в документации и примерах Apple, мне не удалось его найти.
Вот что у меня есть:
@Model
class Thing {
var name: String = ""
var comment: String = "no comment"
var recordType: String = "0"
var count: Int = 0
init(name: String, comment: String, recordType: String, count: Int) {
self.name = name
self.comment = comment
self.recordType = recordType
self.count = count
}
}//class
struct CreateNewThing: AppIntent {
static var title: LocalizedStringResource = "Create New Thing"
static var description = IntentDescription("Opens the app and moves to the Add Thing screen.")
static var openAppWhenRun: Bool = true
@AppStorage("navigateToThingAddView") private var navigateToThingAddView: Bool = false
@MainActor
func perform() async throws -> some IntentResult {
navigateToThingAddView = true
return .result()
}
}//create new thing
struct ThingAddDialog: AppIntent {
static var title: LocalizedStringResource = "Add Thing Dialog"
static var description = IntentDescription("Prompt the user for a name and comment for a new Thing.")
static var openAppWhenRun: Bool = true
@Parameter(title: "Name", default: "")
var name: String
@Parameter(title: "Comment", default: "No comment")
var comment: String
@MainActor
func perform() async throws -> some ProvidesDialog & ShowsSnippetView {
// Logic to navigate to the Add Thing dialog view
//navigateToThingDialog = true
let dialog = IntentDialog(
full: "What is the name of the new Thing?",
supporting: "I have opened the Add Thing Dialog.")
let answer = $name.needsValueError("Provide a name")
name = answer.description
saveThing(name: name, comment: comment)
return .result(dialog: dialog)
}
@MainActor
private func saveThing(name: String, comment: String) {
let newThing = Thing(name: name, comment: comment, recordType: "0", count: 0)
// Add newThing to SwiftData
let container = try! ModelContainer(for: Thing.self)
container.mainContext.insert(newThing)
try? container.mainContext.save()
}
}
struct ThingShortcuts: AppShortcutsProvider {
static var shortcutTileColor = ShortcutTileColor.navy
static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: CreateNewThing(),
phrases: [
"Create a new Thing in \(.applicationName)"
],
shortTitle: "Create a Thing",
systemImageName: "document.badge.plus"
)
AppShortcut(
intent: ThingAddDialog(),
phrases: ["Add Dialog in \(.applicationName)"],
shortTitle: "Add Thing Dialog",
systemImageName: "plus.square"
)
}//var
}//thing shortcuts
Будем признательны за любые рекомендации. Xcode 16.1, iOS 18.1
Я пытаюсь настроить ярлыки и AppIntents, чтобы позволить пользователю вызывать Siri и открывать диалоговое окно для создания новой записи с двумя или более атрибутами модели SwiftData. Я успешно написал код для Siri, чтобы открыть приложение, и для Siri, чтобы открыть приложение и перейти на страницу, чтобы добавить запись, но мне не удалось захватить ответ пользователя из приглашения Siri и сохранить его в новых записях. Если это описано в документации и примерах Apple, мне не удалось его найти. Вот что у меня есть: [code]@Model class Thing {
var name: String = "" var comment: String = "no comment" var recordType: String = "0" var count: Int = 0
static var title: LocalizedStringResource = "Create New Thing" static var description = IntentDescription("Opens the app and moves to the Add Thing screen.") static var openAppWhenRun: Bool = true
@AppStorage("navigateToThingAddView") private var navigateToThingAddView: Bool = false
@MainActor func perform() async throws -> some IntentResult { navigateToThingAddView = true return .result() } }//create new thing
struct ThingAddDialog: AppIntent {
static var title: LocalizedStringResource = "Add Thing Dialog" static var description = IntentDescription("Prompt the user for a name and comment for a new Thing.")
static var openAppWhenRun: Bool = true
@Parameter(title: "Name", default: "") var name: String
@Parameter(title: "Comment", default: "No comment") var comment: String
@MainActor func perform() async throws -> some ProvidesDialog & ShowsSnippetView { // Logic to navigate to the Add Thing dialog view //navigateToThingDialog = true
let dialog = IntentDialog( full: "What is the name of the new Thing?", supporting: "I have opened the Add Thing Dialog.")
let answer = $name.needsValueError("Provide a name") name = answer.description
// Add newThing to SwiftData let container = try! ModelContainer(for: Thing.self) container.mainContext.insert(newThing)
try? container.mainContext.save() } }
struct ThingShortcuts: AppShortcutsProvider { static var shortcutTileColor = ShortcutTileColor.navy
static var appShortcuts: [AppShortcut] {
AppShortcut( intent: CreateNewThing(), phrases: [ "Create a new Thing in \(.applicationName)" ], shortTitle: "Create a Thing", systemImageName: "document.badge.plus" )
Я пытаюсь настроить ярлыки и аппараты, чтобы позволить пользователю вызвать Siri и открыть диалог для создания новой записи с двумя или более атрибутами модели SwiftData. Я успешно кодировал для Siri, чтобы открыть приложение и для того, чтобы Siri...
Я использовал собственное намерение для удовлетворения своих требований, но когда я вызываю API, Siri не ждет ответа API, чтобы показать пользователю следующее сообщение, и Siri остановилась сама, предоставьте какое-либо решение по этому поводу....
Я использовал собственное намерение для удовлетворения своих требований, но когда я вызываю API, Siri не ждет ответа API, чтобы показать пользователю следующее сообщение, и Siri остановилась сама, предоставьте какое-либо решение по этому поводу....
Я пытаюсь понять, как реализовать AppIntents и Shortcuts в приложении iOS. Я могу добавить ярлык для открытия приложения в следующий код как OpenThing.swift. После добавления ярлыка я могу коснуться ярлыка и открыть приложение, а также активировать...
У меня есть несколько различных повторяющихся настроек будильников для разных недель месяца. Я устанавливаю их вручную каждое воскресенье. Но иногда я просыпаюсь раньше времени будильника и хочу пропустить повторяющиеся будильники на этот день....