在 SwiftUI 中从@ObservedObject 获取更新值
Getting the updated value from @ObservedObject in SwiftUI
我试图在用户登录时更改视图,即 isAuthenticated 在 Authentication [=44 中更新时=], 但它永远不会得到新的值,我不确定我是否理解正确。
身份验证
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!")
}
}
到目前为止一切正常,用户通过身份验证,打印 "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 函数
LoginView
struct LoginView: View{
@ObservedObject var auth = Authentication()
var body: some View {
VStack(){
Button(action: {
self.auth.login()
}) {
LoginButtonContent(state: "Login")
}
}
}
}
当你说
@ObservedObject var auth = Authentication()
...在两个不同的视图中,这是两个不同的身份验证对象。一个发生的事情不会影响另一个发生的事情。
如果您的目标是在视图之间共享单个身份验证对象,则需要 @EnvironmentObject
。
我试图在用户登录时更改视图,即 isAuthenticated 在 Authentication [=44 中更新时=], 但它永远不会得到新的值,我不确定我是否理解正确。
身份验证
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!")
}
}
到目前为止一切正常,用户通过身份验证,打印 "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 函数
LoginView
struct LoginView: View{
@ObservedObject var auth = Authentication()
var body: some View {
VStack(){
Button(action: {
self.auth.login()
}) {
LoginButtonContent(state: "Login")
}
}
}
}
当你说
@ObservedObject var auth = Authentication()
...在两个不同的视图中,这是两个不同的身份验证对象。一个发生的事情不会影响另一个发生的事情。
如果您的目标是在视图之间共享单个身份验证对象,则需要 @EnvironmentObject
。