在更新之前如何检查Firestore文档是否存在?

时间:2017-12-25 23:33:13

标签: ios swift firebase google-cloud-firestore

我是Swift的新手,也是Firestore的新手,我遇到了一个无法解决的问题。我有下面的代码应该检查Firestore中UserReference位置的文档。如果它不存在,它应该创建一个新文档,其中包含我之前从facebook上获取的相关用户信息。

这就是UserReference看起来像self.UserReference = self.db.collection("users").document(UserID as! String),其中UserID来自Facebook图形请求。接下来,它将运行一个事务来提取文档,使用最新的Facebook信息更新用户文档(假设这不是新用户),然后将文档更新到Firebase Firestore。

let db = Firestore.firestore()
var fbUserUpdate = User(
    firstName: String(),
    lastName: String(),
    email: String(),
    <extra stuff>)

func updateFacebookInfoToFirestore(completion: @escaping (_: User?, _: Error?) -> Void) {
    // Check if user exists, if not create new user
    UserReference!.getDocument { (document, error) in
        if document != nil {
            // continue
        } else {
            self.UserReference.setData(self.fbUserUpdate.dictionary)
        }
    }

    // Now pull data and update based on most recent facebook info.
    db.runTransaction({ (transaction, errorPointer) -> Any? in

        // Read data from Firestore inside the transaction, so we don't accidentally
        // update using staled client data. Error if we're unable to read here.
        let UserSnapshot: DocumentSnapshot
        do {
            try UserSnapshot = transaction.getDocument(self.UserReference!)
        } catch let error as NSError {
            errorPointer?.pointee = error
            return nil
        }

        // This will overwrite the fbUserUpdate Struct with the updated information.
        guard var dbUser = User(dictionary: UserSnapshot.data()) else {
            let error = NSError(domain: "Domain", code: 0, userInfo: [
                NSLocalizedDescriptionKey: "Unable to write to userdata at Firestore path: \(self.UserReference!.path)"
                ])
            errorPointer?.pointee = error
            return nil
        }

        // Update from Facebook
        dbUser.firstName = self.fbUserUpdate.firstName
        dbUser.lastName = self.fbUserUpdate.lastName
        dbUser.email = self.fbUserUpdate.email

        // Load new data to firestore
        transaction.setData(dbUser.dictionary, forDocument: self.UserReference!, options: SetOptions.merge())
        return nil
    }) { (object, error) in
        if let error = error {
            print(error)
        } else {
            // nothing yet
        }
    }
}

然而,当我在我的应用程序中运行它时,当我到达UserReference!.getDocument闭包时,它跳过闭包,然后事务没有按预期工作,因为try UserSnapshot = transaction.getDocument(self.UserReference!)返回因为没有文档存在,所以为空。

我认为问题出在.getDocument关闭,但我不知道自己哪里出错了。我尽力模仿FriendlyEats firestore示例代码,但我已经陷入困境,需要额外的眼睛。

0 个答案:

没有答案