I considered this a continutation of the thread in the link below. I was going to reply to the thread but it's closed.
@PointOfNilReturn - @teeeeeegz - @pghinman - Did you guys ever got a solution to the original question?
https://www.hackingwithswift.com/forums/swiftui/how-to-handle-first-time-launch-experience-when-icloud-is-required/861
I have been thinking about it and to me the best way to pre-load data would be to check if the data exists before showing it in a view, if it does, check for duplicates and delete them, instead of checking NSUbiquitousKeyValueStore
.
Please let me know if you guys find a better solution.
Here is a quick example of I'm thinking.
Present Data
struct DogsView: View {
@StateObject var dogViewModel = DogViewModel()
// Capture NOTIFICATION
var didRemoteChange = NotificationCenter.default.publisher(for: .NSPersistentStoreRemoteChange).receive(on: RunLoop.main)
var body: some View {
NavigationView{
VStack{
List(dogViewModel.dogs, id: \.self, selection: $selectionServices) { dog in
// show dogs
}
.onAppear{
dogViewModel.loadDogs()
}
// Do something on NOTIFICATION
.onReceive(self.didRemoteChange){ _ in
dogViewModel.loadDogs()
}
.refreshable{
dogViewModel.loadDogs()
}
}
}
}
}
Core Data transactions
class DogViewModel: ObservableObject{
let manager: CoreDataManager
@Published var dogs: [Dog] = []
init(coreDataManager: CoreDataManager = .instance){
self.manager = coreDataManager
loadDogs()
}
// ADDS DELETES, UPDATES etc.
func loadDogs(){
let request = NSFetchRequest<Dog>(entityName: "Dog")
do{
dogs = try manager.context.fetch(request)
for dog in dogs{
// delete duplicates and update dogs
}
}catch let error{
print("Error fetching dogs. \(error.localizedDescription)")
}
}
func save(){
self.manager.save()
}
}