【问题标题】:Getting the updated value from @ObservedObject in SwiftUI在 SwiftUI 中从 @ObservedObject 获取更新的值
【发布时间】:2020-02-26 00:56:36
【问题描述】:

我试图在用户登录时更改视图,即 isAuthenticatedAuthentication 类中更新,但它从未获得新值,我不确定我是否正确理解了所有内容。

身份验证

class Authentication: ObservableObject{

    @Published var email: String = ""
    @Published var password: String = ""
    @Published var isAuthenticated : Bool = false

    func login(){
        AppDelegate._bc.authenticateEmailPassword(email,
                                                  password: password,
                                                  forceCreate: false,
                                                  completionBlock: onAuthenticate,
                                                  errorCompletionBlock: onAuthenticateFailed,
                                                  cbObject: nil)
    }

    func onAuthenticate(serviceName:String?, serviceOperation:String?, jsonData:String?, cbObject: NSObject?) {

        /............./

        UserDefaults.standard.set(true, forKey: "HasAuthenticated")
        self.isAuthenticated.toggle()
        print("Login DONE!")
    }
}

到目前为止一切正常,用户通过身份验证,它打印“登录完成!”并将 isAuthenticated 值更新为 true。

但在 AuthView 中它没有收到新值

AuthView

struct AuthView: View {

    @ObservedObject var auth = Authentication()

    var body: some View {
        NavigationView{
            VStack{
                /............./

                LoginView()

                NavigationLink(destination: ProfileView(), isActive: $auth.isAuthenticated) {
                    Text("")
                }
            }
        }
    }
}

在这里我调用 login 函数

登录视图

struct LoginView: View{

    @ObservedObject var auth = Authentication()

    var body: some View {
        VStack(){
            Button(action: {
                self.auth.login()
            }) {
                LoginButtonContent(state: "Login")
            }
        }
    }
}

【问题讨论】:

    标签: ios swift swiftui combine


    【解决方案1】:

    当你说

    @ObservedObject var auth = Authentication()
    

    ...在两个不同的视图中,它们是两个不同的身份验证对象。一个发生的事情不会影响另一个发生的事情。

    如果您的目标是在视图之间共享单个身份验证对象,则需要@EnvironmentObject

    【讨论】:

    • 哦,我之前试过这个,但只是在 AuthView 中将其更改为 @EnvironmentObject 而不是在两个视图中,我现在得到它并且它正在工作,非常感谢您的帮助。
    猜你喜欢
    • 2020-08-10
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2022-10-19
    相关资源
    最近更新 更多