I am returning JSON from a remote server using the Result Type in Swift 5.
I've tried all kinds of things, but it just won't save. Any help would go a long way.
The data is returning from the server just fine. URLSession.shared.jsonDecodableTask is a snippet I found on SO.
newData has all the correct values.
My code looks as follows:
URLSession.shared.jsonDecodableTask(with: urlComponents.url!) { (result: Result<MyDataRoot, Error>) in
switch result {
case .success(let response):
let managedContext = self.appDelegate?.persistentContainer.viewContext
var count: Int = 0
for d in response.data {
let newData = NSEntityDescription.insertNewObject(forEntityName: "NewEntity", into: managedContext!)
newData.setValue("val1", forKey: "prop1")
newData.setValue("val2", forKey: "prop2")
do {
try managedContext?.save()
count += 1
} catch {
print("Error saving context: \(error)")
}
}
case .failure(let error):
print("Failure: \(error)")
}
}.resume()
I also printed out the location of the db using the following:
#if os(iOS) && targetEnvironment(simulator)
// New variable location for iOS Simulator Filesystem...
if let last = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
print("Documents Directory: \(last)")
}
#endif