-0.7 C
New York
Wednesday, December 4, 2024

ios – Swift AppIntents and Shortcuts Do Not Work when Making an attempt to Navigate to a Completely different View


I am struggling to know tips on how to implement AppIntents and Shortcuts in an iOS app. I’m able to add a shortcut for opening the app within the following code as OpenThing.swift. After including the Shortcut I can faucet the Shortcut and open the app and I can activate Siri and open the app. Nevertheless, with CreateNewThing.swift I’ve not been in a position to uncover tips on how to open the app and navigate to the ThingAddView. When tapping or talking, the app opens, however doesn’t navigate to the ThingAddView.

It is a stripped down model of all of the code wanted to run the app as is:

import Basis
import AppIntents
import SwiftUI
import SwiftData


@important
struct ThingIntentNavApp: App {
    
    @AppStorage("navigateToThingAddView") personal var navigateToThingAddView: Bool = false
    
    var physique: some Scene {
        WindowGroup {
            ThingListView()
                .onAppear {
                    if dataStore.navigateToThingAddView {
                        dataStore.navigateToThingAddView = false // Reset flag
                    }
                }
        }
        .modelContainer(for: [Thing.self])
    }
    
    init() {
        print(URL.applicationSupportDirectory.path(percentEncoded: false))
        ThingShortcuts.updateAppShortcutParameters()
    }
}

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 Factor",
                systemImageName: "doc.badge.plus"
            )
        
            AppShortcut(
                intent: OpenThing(),
                phrases: [
                    "Open Thing in (.applicationName)"
                ],
                shortTitle: "Open Factor",
                systemImageName: "gear"
            )
        
    }//var
}//factor shortcuts

@Mannequin
class Factor {

    var title: String = ""
    var remark: String = "no remark"
    var recordType: String = "0"
    var rely: Int = 0

    init(title: String, remark: String, recordType: String, rely: Int) {
        self.title = title
        self.remark = remark
        self.recordType = recordType
        self.rely = rely
    }
    
}//class



struct OpenThing: AppIntent {

    static var title: LocalizedStringResource = "Open Factor"
    
    static var description = IntentDescription("Opens the app.")
    
    static var openAppWhenRun: Bool = true

    @MainActor
    func carry out() async throws -> some IntentResult {
        
        return .consequence()
    }
    
  
}//create new guide

struct CreateNewThing: AppIntent {
    
    static var title: LocalizedStringResource = "Create New Factor"
    static var description = IntentDescription("Opens the app and strikes to the Add Factor display screen.")
    static var openAppWhenRun: Bool = true

    @AppStorage("navigateToThingAddView") personal var navigateToThingAddView: Bool = false

    @MainActor
    func carry out() async throws -> some IntentResult {
        navigateToThingAddView = true

        return .consequence()
    }
}

@Observable
class DataStore {
    
    static let shared = DataStore()
    
    var navigateToThingAddView: Bool = false
    
    init() {}
    
}//class


struct ThingAddView: View {
    
    @Surroundings(.modelContext) personal var context
    @Surroundings(.dismiss) var dismiss
    @Surroundings(.horizontalSizeClass) var sizeClass
    
    @State personal var title: String = ""
    @State personal var remark: String = ""
    @State personal var recordType: String = ""
    @State personal var rely: Int = 0
    
    
    var physique: some View {
        NavigationStack {
            Kind {
                Textual content("Identify:")
                TextField("", textual content: $title)
                
                Textual content("Remark:")
                TextField("", textual content: $remark)
                    .textFieldStyle(.roundedBorder)
                
                Textual content("File Kind:")
                TextField("", textual content: $recordType)
                    .textFieldStyle(.roundedBorder)
            }
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button("Cancel") { dismiss() }
                }
                ToolbarItem(placement: .topBarTrailing) {
                    Button {
                        saveNewThing()
                        dismiss()
                    } label: {
                        Textual content("Save")
                    }
                }
            }//toolbar
            .navigationTitle("Factor Add View")
            .navigationBarTitleDisplayMode(.inline)
        }//nav
    }//physique
    
    personal func saveNewThing() {
        
        let newThing = Factor(
            title: title,
            remark: remark,
            recordType: recordType,
            rely: rely
        )//new factor
        
        context.insert(newThing)
        
        do {
            strive context.save()
        } catch {
            print(error.localizedDescription)
            //dataStore.contextSaveError = "New Guide context save failed."
        }
    }//save factor

}//struct

struct ThingDetailView: View {
    
    var selectedThing: Factor?
    
    var physique: some View {
        
        if let t = selectedThing {
            NavigationStack {
                VStack {
                    Textual content(t.title)
                    Textual content(t.remark)
                    Textual content(t.recordType)
                }
            }
        }//if let
    }//physique
}//struct

struct ThingListView: View {
    
    @Surroundings(.modelContext) personal var context
    @Surroundings(.dismiss) var dismiss
    
    @AppStorage("navigateToThingAddView") personal var navigateToThingAddView: Bool = false
    
    @Question(kind: Factor.title) var issues: [Thing]
    @State personal var selectedThing: Factor?
    
    @State personal var showThingAddView: Bool = false
    @State personal var dataStore = DataStore.shared
    
    var physique: some View {
        NavigationSplitView {
            
            HStack {
                Textual content("Issues")
                    .font(.title).fontWeight(.daring)
                    .padding(.main, 20)
                Spacer()
                
                Menu {
                    
                    Button(motion: {
                        showThingAddView = true
                    }, label: {
                        Label("Add Factor", systemImage: "plus")
                    })
                    
                } label: {//menu
                    Picture(systemName: "ellipsis.circle")
                        .font(.system(dimension: 30))
                }//menu
                .padding(.trailing)
            }//h on high
            
            VStack {
                Record(choice: $selectedThing) {
                    ForEach(issues) { factor in
                        NavigationLink(vacation spot: ThingDetailView(selectedThing: factor)) {
                            Textual content(factor.title)
                        }
                    }
                }//listing
                .fullScreenCover(isPresented: $showThingAddView) {
                    ThingAddView()
                }
            }//v
            .onAppear {
                if issues.isEmpty {
                    createSampleThings()
                }

                if navigateToThingAddView {
                    showThingAddView = true
                    navigateToThingAddView = false // Reset flag
                }
                
            }
        } element: {
            VStack {
                if selectedThing != nil {
                    ThingDetailView(selectedThing: selectedThing)
                } else {
                    WelcomeView()
                }
            }//v
        }//element
    }//physique
    
    
    //MARK: -  Samples
    
    func createSampleThings() {

        let thing1 = Factor(
            title: "To Kill a Mockingbird",
            remark: "A traditional novel set within the American South.",
            recordType: "Harper Lee",
            rely: 5
        )
        
        let thing2 = Factor(
            title: "1984",
            remark: "A dystopian novel.",
            recordType: "George Orwell",
            rely: 4
        )
        
        let thing3 = Factor(
            title: "The Nice Gatsby",
            remark: "A novel in regards to the American Dream.",
            recordType: "F. Scott Fitzgerald",
            rely: 4
        )
        
        let thing4 = Factor(
            title: "Delight and Prejudice",
            remark: "A romance novel set in Regency England.",
            recordType: "Jane Austen",
            rely: 5
        )
        
        let thing5 = Factor(
            title: "The Catcher within the Rye",
            remark: "A novel about teenage alienation.",
            recordType: "J.D. Salinger",
            rely: 3
        )
        
        context.insert(thing1)
        context.insert(thing2)
        context.insert(thing3)
        context.insert(thing4)
        context.insert(thing5)
        
        do {
            strive context.save()
        } catch {
            print("Error saving knowledge: (error)")
        }
    }//create samples
    
}//struct

struct WelcomeView: View {
    var physique: some View {
        Textual content("Put the common welcome view right here")
    }
}

Any steering could be appreciated. Xcode 16.1, iOS 18.1.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles