Hi Guys, this is my first post. I'm having problem loading data from CoreData and I've been grinding it for two days.
My approach is to fetch data from API and store them directly into CoreData which I successfully did.
The following is the function and I called it in onAppear
of the list.
I use a bool to store in UserDefaults
whether data has been store into CoreData so that next time app is opened API won't be called and load from CoreData
func fetchPersonsFromAPI() {
let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json")!
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else {
debugPrint("No data in response \(error?.localizedDescription ?? "Unknown error")")
return
}
let decoder = JSONDecoder()
decoder.userInfo[CodingUserInfoKey.managedObjectContext!] = moc
do {
let decoded = try decoder.decode([CDPerson].self, from: data)
if moc.hasChanges {
try? moc.save()
UserDefaults.standard.set(true, forKey: "SavedToCD")
print("Successfully saved to CD")
}
} catch {
print("Decoding Failed: \(error.localizedDescription)")
}
}.resume()
}
This is the code for managedObjectContext and FetchRequest just like Xcode autopopulated code.
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: CDPerson.entity(), sortDescriptors: [
NSSortDescriptor(key: "isActive", ascending: false),
NSSortDescriptor(key: "name", ascending: true)]) var persons: FetchedResults<CDPerson>
In the detail view for friends list, I used the following function to fetch full Person object using ID of friend object so that I can pass that full Person object to the next view when it is tapped.
func fetchFriendsFromCD(person: CDPerson) {
var friendArray: [CDPerson] = []
for friend in person.friendArray {
let fetchRequest: NSFetchRequest<CDPerson> = CDPerson.fetchRequest()
fetchRequest.fetchLimit = 1
fetchRequest.predicate = NSPredicate(format: "id = %@", friend.wrappedID)
let object = try? moc.fetch(fetchRequest).first
friendArray.append(object!)
}
friendList = friendArray
print("Fetched friend list from core data")
}
The problem is
Everything is working perfectly fine on the first launch. Then I stopped and run again then only blank screen appeared. I checked FetchResult count and it's 0. Seems like it's not loading properly.
Please check the source code for complete project
https://github.com/zunemoe/HackingWithSwift-SwiftUI100/tree/main/Day61-FriendFace
Sorry for my english :)