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

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật