【发布时间】:2021-05-01 16:35:08
【问题描述】:
我是 Swift UI 和 MongoDB 领域的新手。我正在尝试在文本框中显示用户的电子邮件(来自他们各自的自定义用户数据),但我得到了一个奇怪的结果,我不知道如何解决。我一直在半盲地尝试各种事情,希望有什么能奏效,但到目前为止还没有运气。我正在使用电子邮件/密码授权,所以我知道电子邮件/密码不会存储在用户自定义数据中(我认为),但这只是我正在尝试做的一个示例。
我目前的代码如下。
struct HomeView: View {
let user = app.currentUser!
@State var isLoggingOut = false
var body: some View {
let userEmail = user.customData["email"] ?? "no email"
let userPassword = user.customData["password"] ?? "no password"
let userDisplay = user.customData["display"] ?? "no display"
let userName = user.customData["fullName"] ?? "no name"
ZStack {
Rectangle().foregroundColor(.yellow)
VStack {
Spacer()
Text("Home")
HStack {
Text("Email").frame(width: 100)
Spacer()
Text(String(reflecting: userEmail))
}.padding(.vertical)
HStack {
Text("Password").frame(width: 100)
Spacer()
Text(String(describing: userPassword))
}.padding(.vertical)
HStack {
Text("Display").frame(width: 100)
Spacer()
Text(String(describing: userDisplay))
}.padding(.vertical)
HStack {
Text("Full name").frame(width: 100)
Spacer()
Text(String(describing: userName))
}.padding(.vertical)
Spacer()
Button("Log Out") {tryLogOut()}
}.padding(40)
if isLoggingOut {LoginView()}
}
}
func tryLogOut() {
app.currentUser?.logOut {error in}
self.isLoggingOut = true
}
}
使用测试用户登录后,这是我在正确的 HStack 文本框(例如,顶部的电子邮件文本框)中得到的:
Email Optional(RealmSwift.AnyBSON.string("test123@gmail.com"))
显然我想要得到的是:
Email test123@gmail.com
我做错了什么?其他一切都按预期工作,但这个问题让我头疼。任何帮助将不胜感激。
也仅供参考 - 根据 Atlas,我试图在文本框中显示的所有内容都以字符串形式存储在数据库中,因此我看不到问题所在。但是在我的NewUserRegistrationView 中,当我创建新的用户文档时,我使用以下代码,我不确定在插入文档之前是否与AnyBSON 类型有任何冲突。
struct NewUserRegistrationView: View {
// Email, password, displayName, and fullName obtained from TextFields in the body ...
// createUserDocument() is called after registering and confirming the user
func createUserDocument() {
let credentials = Credentials.emailPassword(
email: self.email,
password: self.password)
app.login(credentials: credentials) {result in
switch result {
case .failure:
self.statustext = "Document creation failed, try again"
case .success(let user):
let client = user.mongoClient("mongodb-atlas")
let database = client.database(named: "AppDatabase")
let collection = database.collection(withName: "userDocuments")
collection.insertOne([
"userID": AnyBSON(user.id),
"email": AnyBSON(self.email),
"password": AnyBSON(self.password),
"display": AnyBSON(self.display),
"fullName": AnyBSON(self.fullName)
]) { result in
switch result {
case .failure:
self.statustext = "Could not add document"
case .success(let newObjectId):
self.statustext = "Inserted document with objID: \(newObjectId)"
self.isDone = true
}
}
}
}
}
【问题讨论】: