我將 swift(UI) 與 firebase 和 Google SignIn 一起使用。到目前為止登錄效果很好,但是當我開始使用新用戶時,下面的代碼失敗了——沒有致命錯誤只是沒有向 Firestore 添加新的用戶檔案,因為它似乎認為它已經檢索到了一個它無法檢索到的檔案因為具有指定 ID 的 ID 不存在。我的猜測是錯誤在以下部分:
if let error = error as NSError? {
print("Error getting document: \(error.localizedDescription)")
self.setFirestoreUser()
}
完整的功能:
func fetchUser(documentId: String) {
let docRef = Firestore.firestore().collection("users").document(documentId)
print("User id: \(documentId) ( via fetchUser )")
docRef.getDocument { document, error in
if let error = error as NSError? {
print("Error getting document: \(error.localizedDescription)")
self.setFirestoreUser()
}
else {
if let document = document {
do {
print("Working on coding to User.self")
self.appUser = try document.data(as: User.self)
self.fetchSites()
}
catch {
print("func - fetchUser() error: \(error)")
}
}
}
}
}
引數“documentId”是從 google 簽名程序中傳遞的
后續函式為這個新用戶創建新的 Firestore 檔案:
func setFirestoreUser() {
let googleUser = GIDSignIn.sharedInstance.currentUser
let db = Firestore.firestore()
self.appUser.emailAddress = googleUser?.profile?.email ?? "Unknown"
self.appUser.userGivenName = googleUser?.profile?.givenName ?? ""
self.appUser.userFirstName = googleUser?.profile?.name ?? ""
self.appUser.userProfileURL = googleUser?.profile!.imageURL(withDimension: 100)!.absoluteString ?? ""
do {
try db.collection("users").document(googleUser?.userID ?? "UnknownID").setData(from: self.appUser)
self.fetchUser(documentId: googleUser?.userID ?? "")
} catch {
print(error)
}
}
uj5u.com熱心網友回復:
呼叫getDocument對不存在檔案的參考不是錯誤(據我所知),并且會回傳一個DocumentSnapshot. 要檢測檔案是否存在,請檢查快照上的exists屬性,而不是(僅)檢查錯誤。
if let document = document {
if !document.exists {
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483981.html
下一篇:IntelliJ中的自動靜態匯入
