I decode json data from an iPhone to a watch and store it into an object (custom class: PeopleObj) which is declared as @ObservableObject. However, the contenview containing this object doesn't get the data
This is the data model:
struct Person: Codable {
var pid : UUID
var dept: String
var name: String
init(pid: UUID, dept: String, name: String){
self.pid = pid
self.dept = dept
self.name = name
}
}
class PeopleObj: ObservableObject, Identifiable , Codable{
@Published var people: [Person] = []
// get codable
init() { }
enum CodingKeys: CodingKey {
case people
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(people, forKey: .people)
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
people = try container.decode(Array.self, forKey: .people)
}
}
Following is the decode part at WatchOS, here I get the json data as a reply on a request and decode it into the peopleObj:
let jsonEncoder = JSONEncoder()
do {
let jsonDataRequest = try jsonEncoder.encode(request)
print("send request")
self.session?.sendMessageData(jsonDataRequest, replyHandler: { response in
print(">>>>>>>>>>>>>>>>> DATA-Reply vom iPhone received: \(response)")
DispatchQueue.main.async {
let jsonDecoder = JSONDecoder()
do {
self.peopleObj = try jsonDecoder.decode(PeopleObj.self, from: response)
for person in self.peopleObj.people {
print("received person: \(person.name), dept \(person.dept)")
// here it prints correctly
}
} // End do decode
catch { print("decode catch!!!!!!!") }
} // Dispatch main
},
errorHandler: { error in
print("Error sending message: %@", error)
}) // sendMessageData
} // End do decode
catch { print("encode catch!!!!!!!") }
This is the contenview, observing the object:
struct ContentView: View {
@ObservedObject var peopleObj: PeopleObj
var body: some View {
VStack {
List(peopleObj.people, id: \.pid) { person in
HStack {
Text("name: \(person.name)")
Spacer()
Text("dept: \(person.dept)")
}
}
}
}
}
I tried decoding the json into a struct and then manualy add the values to the peopleObj - that works but doesn't seem to be the correct process to me! I can't explain why, guess it has something to do with value vs referencing.
Any help and or idea is more than welcome!!!!!
Edit: The peopleObj is defined in the HostingController:
class HostingController: WKHostingController<ContentView> , WCSessionDelegate{
@ObservedObject var peopleObj:PeopleObj = PeopleObj()
The ContentView is called from the HostingController
override var body: ContentView {
return ContentView(peopleObj: peopleObj)
}