I am trying to create a DataModel for my SwiftUI Screen. The problem I am facing is that I use Core NFC to scan a NFCTag (perform some tasks) and then I want to update the SwiftUI Screen. The data fetch/manipulation occurs asynchronous.
View
struct NFCTest: View {
@EnvironmentObject var nfcController: NFCController
var body: some View {
VStack {
Button(action: {
self.nfcController.beginScanning()
}) {
Text("Button")
}
NFCController
final class NFCController: UIViewController, ObservableObject {
@Published var someObject :ObjectStruct //someObject contains a @Published var someVar
//Tag detected
func doSomeAsyncCalls {
//calling functions in other swift files. runs async on another thread. Should change someVar at the end of the calculation
}
Now the problem is that nested Observable Objects to do not work in SwiftUI. I tried to make an observable var in NFCController and inside that var I created a published var. But the change is not triggered in SwiftUI.
Are there any concepts to solve this async data flow problem?
Here is possible approach (scratchy)
final class NFCController: UIViewController, ObservableObject {
@Published var someObject :ObjectStruct
func doSomeAsyncCalls {
// .. some other code here
DispatchQueue.global(qos: .background).async { // < mimic async call
// .. some calculations
DispatchQueue.main.async {
self.someObject.someVar = result
self.objectWillChange.send() // << here !!
}
}
}
}
of course related view should has dependency on this controller members somewhere in body
, otherwise rendering engine could just ignore update.