Jagan Mohan Sahu
Jagan Mohan Sahu

Reputation: 33

DispatchQueue.main.async does not return to the main thread - SwiftUI

struct ContentView: View {
    @State var manager = HtpAuth()
    
    var body: some View {
    
        if manager.authenticated {
            Text("Login Successful!!")
        }

        // 2 textfields for username and password and 
        // a login button to call checkForAuth function
        //...
    }
}

class HttpAuth: ObservableObject {
    var didChange = PassthroughSubject<HttpAuth, Never>()

    var authenticated = false {
        didSet {
            didChange.send(self)
        }
    }

    func checkForAuth(username: String, password: String) {

        //REST API call
        URLSession.shared.data.task(with: loginRequest) { data, response, error in 
            guard let data = data else { return }
            let finalData = try! JSONDecoder().decode(ServerMessage.self, from: data)
    
            DispatchQueue.main.async {
                self.authenticated = true
            }
        }.resume()
    }
}

I am getting response from the server. But after recieving the resposne, I want to return to the main thread to display some other view. I am using DispatchQueue.main.async for this purpose, but it does not work. The label "Login Successfull!!" never appears, after successful login.

Upvotes: 2

Views: 991

Answers (1)

Asperi
Asperi

Reputation: 257779

Use instead standard Published and ObservedObject wrappers as below

struct ContentView: View {
    @ObservedObject var manager = HtpAuth()   // use @StateObject in SwiftUI 2

    ...
    

class HttpAuth: ObservableObject {
    @Published var authenticated = false
    ...

Upvotes: 2

Related Questions