0

I'm new to programming and I apologize in advance if my code makes no sense. I am completely lost with trying to fetch some json using an HTTP request and load it into Core Data. I was hoping someone might be able to provide some insight into the mistakes I have made... running this code causes an immediate crash.

Please let me know if I should provide further information. Thanks for reading.

class DataProvider {
    let persistentContainer: NSPersistentContainer
    var users: [User]? = []
    
    
    func loadData() {
        let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json")!
        var request = URLRequest(url: url)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "GET"
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                self.persistentContainer.performBackgroundTask { context in
                    let decoder = JSONDecoder()
                    decoder.userInfo[CodingUserInfoKey.managedObjectContext] = context
                    if (try?
                            decoder.decode([User].self, from: data)) != nil {
                        context.perform {
                            let fetchRequest : NSFetchRequest<User> = User.fetchRequest()
                            self.users = try? context.fetch(fetchRequest)
                        }
                    }
                }
            }
        }.resume()
    }
    init(container: NSPersistentContainer) {
        self.persistentContainer = container
    }
}
pakobongbong
  • 123
  • 1
  • 9
  • "running this code causes an immediate crash" At which line? – El Tomato Oct 01 '21 at 04:44
  • @ElTomato Ah... I'm so sorry I'm not too sure how to tell. I am getting this error "Thread 7: "-[NSTaggedPointerString managedObjectContext]: unrecognized selector sent to instance 0xa4fcdc9b8a06c64b"" – pakobongbong Oct 01 '21 at 04:49
  • 1
    Maybe break your code down and try different steps separately because the current code looks quite complex, test he decoding separately and the same for the fetch request, do it without the background context… – Joakim Danielson Oct 01 '21 at 07:05

0 Answers0