【问题标题】:Saving user info to Firestore将用户信息保存到 Firestore
【发布时间】:2020-08-10 13:23:03
【问题描述】:

我使用 Firestore 创建了一个用户,但我无法将其保存到结构中以便稍后获取用户的名字作为标签。我该如何解决?

//create the user
Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
    print(result)
    //check for errors
    if err != nil {
        //there was an error while creating user
        self.showError("Error creating user")
    }//end if
    else {
        //user was created successfully, store name, last name and email
        let db = Firestore.firestore()
        db.collection("users").addDocument(data: ["firstName": firstName, "lastName": lastName, "age": age!, "imageUrl": imageUrl, "email": email, "uid": result!.user.uid]) { (error) in

            if error != nil {
                //show error message
                self.showError("Account created, but database couldn't save name")
            }//end of if
        }//end of db collection

        //save current user
        //This is where I would like to save my user to my struct

        //transition to homescreen
        self.transitionToTabBarVC()
    }//end else

}//end of create user

【问题讨论】:

  • 将结构体转换为类,类是引用类型。不同于具有价值的结构

标签: swift google-cloud-firestore firebase-authentication


【解决方案1】:

您可以像这样检索用户的个人资料信息:

let user = Auth.auth().currentUser
if let user = user {
  let uid = user.uid
  let email = user.email
  let photoURL = user.photoURL
  let displayName = user.displayName
}

如果您想存储其他特定于应用程序的配置文件信息(例如,他们最喜欢的颜色或任何其他特定于您的应用程序的信息),我建议将其存储在 Firestore 中的集合中,该集合不是 命名为users,以防止任何混淆。例如,将其命名为 profiles

然后,创建一个 ProfileRepository 类来获取用户的个人资料,如下所示:

import FirebaseFirestoreSwift

struct UserProfile: Codable {
  var favouriteColour: String
}

class ProfileRepository {

  func getUserProfile(completion: @escaping  (_ profile: UserProfile) -> Void) {
    if let uid = Auth.auth().currentUser?.uid {
      let profileRef = Firestore.firestore().collection("profiles").document(uid)
      profileRef.getDocument { (documentSnapshot, error) in
        do {
          if let profile = try documentSnapshot?.data(as: UserProfile.self) {
            completion(profile)
          }
        }
        catch {
          print(error)
        }
      }
    }
  }

}

请注意,由于大多数 Firebase API 都是异步的,因此您需要使用回调机制将配置文件返回给调用者。在这里,我使用了一个闭包(我个人比代表更喜欢它)。

我也在利用 Firebase 对 Codable 的支持,因此您必须将此行添加到您的 Podfile

pod 'FirebaseFirestoreSwift'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-29
    • 2020-05-17
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多