Hi,
I am in need of some help on how to interact with an API that provides a response as a dictionary which looks like this...
(DictionaryResponseSample.json)
{
"success": true
"payload": [
{
"facility_id": 1234,
"facility_name": "facility_1"
},
{
"facility_id": 1235
"facility_name": "facility_2"
}
]
}
I have no problem directly importing into Core Data when the response is an array as in...
(ArrayResponseSample.json)
[
{
"facility_id": 1234,
"facility_name": "facility_1"
},
{
"facility_id": 1235
"facility_name": "facility_2"
}
]
The code driving this is from Donny Wals Core Data book
From DataImporter.swift
public static var sampleData: Data {
let url = Bundle(for: Self.self).url(forResource: "ArrayResponseSample", withExtension: "json")
return try! Data(contentsOf: url!)
}
public func importData<T: Collection & Decodable>(_ data: Data, as model: T.Type) where T.Element: NSManagedObject {
self._importData(data, as: model)
}
private func _importData<T: Decodable>(_ data: Data, as model: T.Type) {
context.perform { [unowned self] in
let decoder = JSONDecoder()
decoder.userInfo[.managedObjectContext] = self.context
do {
_ = try decoder.decode(model, from: data)
try self.context.save()
self.context.reset()
}
catch {
if self.context.hasChanges {
self.context.rollback()
}
print("Failed to insert models")
print(error)
}
}
}
Called in ContentView.swift...
var body: some View {
VStack {
Button("Import Data") {
let data = DataImporter.sampleData
importer.importData(data, as: [Facility].self)
}
VStack {
List(facilities, id: \.facility_id) { (facility: Facility) in
Text("\(facility.facility_name)")
}
}
}
.padding()
}
I'd like to keep the response metadata (success) in the API so I can confirm the success of a response. I could omit 'success' on the successul API call and use Swift's error handling to determine if the response responded with a success and only return the failure metadata on a failed API call.
It'd be great to just 'slice' off the paylaod array as I could resuse an API response class, but I cannot figure out how to do that
I believe that I am trying to do is very similar to Paul's Whitehouse project here: https://www.hackingwithswift.com/read/7/3/parsing-json-using-the-codable-protocol with the difference being using NSManagedObject classes instead of just Codable classes.
This would be a big breakthrough for me so any help would be greatly appreciated. Thanks in advance!