我有一个名为UserData
的模型,该模型仅用于当前登录的用户。它将数据保存为配置文件数据,用户ID,对Firestore文档的引用等。
我将其作为@EnvironmentObject
注入,以便可以在任何地方访问它。
final class UserData: ObservableObject {
@Published var profile = Profile.default
@Published var loggedIn: Bool = Auth.auth().currentUser != nil ? true : false
@Published var uid: String = ""
@Published var documentReference: DocumentReference = Firestore.firestore().document("")
}
我还有一个带有方法的UserViewModel。
class UserViewModel: ObservableObject {
func login(email: String, password: String, completion: @escaping (Response) -> Void) {
AuthService().login(email: email, password: password) { (response: Response) in
// let error = response.error
completion(response)
}
}
func register(email: String, password: String, firstName: String, lastName: String, completion: @escaping (Response) -> Void) {
AuthService().register(email: email, password: password, firstName: firstName, lastName: lastName) { (response: Response) in
// let error = response.error
completion(response)
}
}
func logout() {
try? Auth.auth().signOut()
}
}
问题出现在视图中
@EnvironmentObject var userData: UserData
var userViewModel = UserViewModel()
func login() {
if self.email == "" || self.password == "" {
self.error = "You must provide both an email and password"
} else {
self.userViewModel.login(email: self.email, password: self.password) { response in
self.userData.profile = response.profile!
self.userData.uid = response.uid
self.userData.documentReference = response.documentReference ?? Firestore.firestore().document("")
UserDefaults.standard.set(response.userDefaults, forKey: "userDefaults")
}
}
}
如您所见,我无法如此轻松地更新此UserModel。我必须逐个更新其每个属性,并且对于注册,我必须做同样的事情。 SceneDelegate中也是如此。我在三个不同的地方有相同的行,分别是登录视图,注册视图和SceneDelegate
self.userData.profile = response.profile!
self.userData.uid = response.uid
self.userData.documentReference = response.documentReference ?? Firestore.firestore().document("")
UserDefaults.standard.set(response.userDefaults, forKey: "userDefaults")
是否有更好的方法来处理此类问题?就像有一个地方来更新此@EnvironmentObject
。在视图中使用它们真的很酷,但是在视图外部更新它们确实很痛苦。另外,由于无法将UserData
传递给UserViewModel
,因此它不能与UserViewModel一起使用。
如何正确使用名为UserData的@EnvironmentObject