0

I use URLSession to connect to a websocket server. With the callback functions I update the var "isConnectionOpen" inside the Model/Service. Even though I use the @Published modifier the update is not redrawing my view. Below you can find a short overview.

Model

var isConnectionOpen = false
func openConnection()

    // callback functions
    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
        print("WebSocket connection opened")
isConnectionOpen = true
}

ViewModel

@Published var model = Model()

View

@ObservedObject var vm: VM

var body: some View {
    Text(vm.model.isConnectionOpen ? "Connected" : "Not connected")
}
1
  • 2
    Is you model a struct or a class? Commented Apr 25, 2022 at 15:47

1 Answer 1

1

here is an example of using @ObservedObject in the parent view you have to declare the object as @StateObject

 class Model: ObservableObject{
    @Published var isConnectionOpen = false
    
    func openConnection(){
        // ...
        // if is completed set isConnectionOpen = true
        isConnectionOpen = true

    }
}

struct ChildView: View{
    @ObservedObject var model: Model

    var body: some View {
        VStack{
            Button("tap-to-connect"){
                model.openConnection()
            }
            Text(model.isConnectionOpen ? "Connected" : "Not connected")

        }
    }
}

struct ParentView: View {
    @StateObject var model = Model()
    var body: some View{
        ChildView(model: model)
//            .onAppear(perform: {
//                // Mark: Connect to server
//                model.openConnection()
//            })
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.