DispatchQueue.main.async 不会 return 到主线程 - SwiftUI

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()
    }
}

我正在从服务器收到响应。但是在收到响应后,我想 return 到主线程以显示其他视图。为此,我正在使用 DispatchQueue.main.async,但它不起作用。标签“登录成功!!”永远不会出现,登录成功后。

改用标准 PublishedObservedObject 包装器,如下所示

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

    ...
    

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