将用户信息保存到Firestore

时间:2020-04-27 03:25:10

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

我已经使用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

1 个答案:

答案 0 :(得分:0)

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

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
}

如果您想存储其他特定于应用程序的配置文件信息(例如,他们喜欢的颜色或您应用程序特有的其他颜色),我建议将其存储在不是 命名为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'