Hello,
I’m encountering the error "Publishing changes from within view updates is not allowed, this will cause undefined behavior". while developing an app using SwiftUI and ARKit.
I have a ObjectTracking class where I update some @Published variables inside a function called processObjectAttributes after detecting objects. However, when I try to update these state variables in the View (like isPositionChecked, etc.), the error keeps appearing.
Here is a simplified version of my code:
class ObjectTracking: ObservableObject {
@Published var isPositionChecked: Bool = false
@Published var isSizeChecked: Bool = false
@Published var isOrientationChecked: Bool = false
func checkAttributes(objectAnchor: ARObjectAnchor,
_ left: ARObjectAnchor.AttributeLocation,
_ right: ARObjectAnchor.AttributeLocation? = nil,
threshold: Float) -> Bool {
let attributes = objectAnchor.attributes
guard let leftValue = attributes[left]?.floatValue else { return false }
let rightValue = right != nil ? attributes[right!]?.floatValue ?? 0 : 0
return leftValue > threshold && (right == nil || rightValue > threshold)
}
func isComplete(objectAnchor: ARObjectAnchor) -> Bool {
isPositionChecked = checkAttributes(objectAnchor: objectAnchor, .positionLeft, .positionRight, threshold: 0.5)
isSizeChecked = checkAttributes(objectAnchor: objectAnchor, .sizeLeft, .sizeRight, threshold: 0.3)
isOrientationChecked = checkAttributes(objectAnchor: objectAnchor, .orientationLeft, .orientationRight, threshold: 0.3)
return isPositionChecked && isSizeChecked && isOrientationChecked
}
func processObjectAttributes(objectAnchor: ARObjectAnchor) {
currentObjectAnchor = objectAnchor
}
}
In my View, I am using @ObservedObject to observe the state of these variables, but the error persists when I try to update them during view rendering.
Could anyone help me understand why this error occurs and how to avoid it? I understand that state should not be updated during view rendering, but I can’t find a solution that works in this case.
Thank you in advance for your help!