UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 61 FriendFace Core Data only load data on first launch

Forums > 100 Days of SwiftUI

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 :)

2      

I'm having problem loading data from CoreData and I've been grinding it for two days

So, what's the problem?

2      

Everything is working perfectly fine on the first launch. Then I stopped and run again then only blank screen appeared. Seems like CoreData is not saving my data permanently

I use the same PersistenceController from Xcode

struct PersistenceController {
    static let shared = PersistenceController()
    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "PersonInfo")

        if inMemory {
            container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("unresolved error \(error), \(error.userInfo)")
            }                        
        }
    }
}

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.