Add Local Persistence using CloudKit & Core Data [closed]

I’m attempting to add local persistence to items fetched from CloudKit using Core Data in my app, but I’m not achieving the desired behavior. Here’s what I aim to accomplish:

  1. User opens the app.
  2. Fetch items from CloudKit.
  3. Display the fetched items.
  4. Save the fetched items to Core Data.

  1. User closes and reopens the app.
  2. Display the saved items from Core Data, as before.
  3. Sync with CloudKit and smoothly update the display if there are any changes.

My approach below is wrong because, as a SO user mentioned: “In SwiftUI the View structs are the view model already you shouldn’t try to use objects or will run into major issues. StateObject is for something else.” I am seeking guidance on the correct way to handle this.

class CloudKitViewModel: ObservableObject {
    @Published var items: [Item] = []
    @Published var selectedItem: Item?
    private var database = CKContainer.default().publicCloudDatabase
    private let persistentContainer: NSPersistentContainer

    init() {
        let container = CKContainer(identifier: "iCloud.com.user.my.project")
        self.database = container.publicCloudDatabase
        
        // Set up Core Data
        persistentContainer = NSPersistentContainer(name: "Model")
        persistentContainer.loadPersistentStores { description, error in
            if let error = error {
                fatalError("Unable to load persistent stores: (error)")
            }
        }
        
        loadSavedItems()
        fetchItems()
    }

    func fetchItems() {
        let query = CKQuery(recordType: "Item", predicate: NSPredicate(value: true))
        database.perform(query, inZoneWith: nil) { records, error in
            if let records = records {
                DispatchQueue.main.async {
                    self.items = records.map { record in
                        Item(
                            id: record.recordID,
                            city: record["City"] as? String ?? ""
                        )
                    }
                    self.saveItemsToCoreData()
                }
            } else if let error = error {
                print("Error fetching records: (error.localizedDescription)")
            }
        }
    }
    
    private func loadSavedItems() {
        let context = persistentContainer.viewContext
        let fetchRequest: NSFetchRequest<Model> = Model.fetchRequest()
        
        do {
            let itemEntities = try context.fetch(fetchRequest)
            self.items = itemEntities.map { entity in
                Item(
                    id: CKRecord.ID(recordName: entity.id ?? ""),
                    city: entity.city ?? ""
                )
            }
        } catch {
            print("Failed to fetch items from Core Data: (error)")
        }
    }

    private func saveItemsToCoreData() {
        let context = persistentContainer.viewContext
        
        // Remove old data
        let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Model.fetchRequest()
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        
        do {
            try context.execute(deleteRequest)
        } catch {
            print("Failed to delete old items from Core Data: (error)")
        }
        
        // Save new data
        items.forEach { item in
            let entity = Model(context: context)
            entity.id = item.id.recordName
            entity.city = item.city
        }
        
        do {
            try context.save()
        } catch {
            print("Failed to save items to Core Data: (error)")
        }
    }
}

Here’s how items are displayed to the user on startup:

struct MyView: View {
    @StateObject private var viewModel = CloudKitViewModel()
    var body: some View {
        NavigationView {
            VStack {
                List {
                    Section {
                        ForEach(viewModel.items) { item in
                            ItemRow(
                                item: item
                            )
                        }
                    }
                }
            }
        }
    }
}

struct Item: Identifiable {
    var id: CKRecord.ID
    var city: String
}

struct ItemRow: View {
    var item: Item
    var body: some View {
        HStack {
            Text(item.city)
        }
    }
}

3

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