How to save data captured from a Background fetch into a SwiftData model

  Kiến thức lập trình

Newbie to SwiftUI here. I am developing an app that will select a random quote (a “Selection”; see definition below) from a JSON file once a day, and then send it to the phone in a local Notification. All this is done in the @main part of the app. When you tap on the Notification, it opens the App and shows the quote (in ContentView). You can then save the quote (I’m using SwiftData).

I have the Background fetch working, and the Notification working with the fetched content. My issue: I need to update the ContentView with the fetched content when the user opens the app.

I tried storing the fetched Selection in a SwiftData model from the “handleRefresh” method, but I get the error: “Accessing Environment’s value outside of being installed on a View. This will always read the default value and will not update. Cannot insert ‘Selection’ in this managed object context because it is not found in the associated managed object model.”

If I can’t save the fetched Selection, how do I access it in ContentView? What’s the best practice?

The data model:

@Model
class Selection: Codable, Hashable {
    let selectedBook: String
    let selectedChapter: Int
    let selectedVerse: String
    let selectedVerseIndex: Int
    var date: Date
    let addVerse: Int
    
    // more below to make it Hashable and Codable

The @main app with the “handleRefresh” method which calls the function to select a new quote in the background:

@main
struct DvarApp: App {
    @Environment(.scenePhase) var scenePhase
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    let modelContainer: ModelContainer
    
    init() {
        do {
            modelContainer = try ModelContainer(for: Selection.self)
        } catch {
            fatalError("Could not initialize ModelContainer")
        }
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .modelContainer(for: Selection.self)
        }
        .onChange(of: scenePhase, initial: false) { oldPhase, newPhase in
            switch newPhase {
            case .background: appDelegate.scheduleAppRefresh()
            default: break
            }
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    
    @Environment(.modelContext) var modelContext
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.dvar.refresh", using: nil) { task in
            self.handleRefresh(task: task as! BGAppRefreshTask)
        }
        return true
    }
    
    func handleRefresh(task: BGAppRefreshTask) {
        task.expirationHandler = {
            task.setTaskCompleted(success: false)
        }
        
        // Fetch new data
        let verse = chooseVerse()
        
        task.setTaskCompleted(success: true)
        
        // Schedule the next background fetch
        self.scheduleAppRefresh()
    }
    
    func scheduleAppRefresh() {
        print("refresh scheduled")
        let request = BGAppRefreshTaskRequest(identifier: "com.dvar.refresh")
        request.earliestBeginDate = Date(timeIntervalSinceNow: 60 * 2)
        do {
            try BGTaskScheduler.shared.submit(request)
        } catch {
            print("Could not schedule app refresh: (error)")
        }
    }
 
}

New contributor

GlennGC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

LEAVE A COMMENT