等待查询在继续之前获取Firestore数据

时间:2018-01-19 12:39:00

标签: swift firebase google-cloud-firestore

我想将文章的用户/作者提取到计算属性中。但这种情况从未发生过,下面的代码会打印1,2,4。

struct Article {
    private let database = Firestore.firestore()

    var authorId: String
    var message: String

    var author: User? {

        print(1)
        var fetchedAuthor: User?
        let semaphore = DispatchSemaphore(value: 0)

        print(2)
        database.collection("users").document(authorId).getDocument { (document, error) in

            print(3)
            guard let user = document.flatMap({User(dictionary: $0.data())}) else {
                print("Could not get author: \(error.debugDescription)")
                semaphore.signal()
                return
            }

            fetchedAuthor = user
            semaphore.signal()
        }

        print(4)

        semaphore.wait()
        print(5)
        return fetchedAuthor
    }
}

2 个答案:

答案 0 :(得分:1)

在@Connor的评论中添加伪/样本代码,因为我刚刚完成了这个。

extension User {
  static func getBy(documentID id: String, completion: @escaping (User)->()) {
    database.collection("users").document(id).getDocument { (document, error) in
        guard let user = document.flatMap({User(dictionary: $0.data())}) else {
            print("Could not get author: \(error.debugDescription)")
            return
        }
        completion(user)
  }
}

然后在你的文章结构中:

struct Article {
  ....
  init(){
    ....
    // Get the user
    User.getBy(documentID: self.userID) { user in
      self.author = user
    }
  }
}

答案 1 :(得分:0)

semaphore.wait() //is for requesting the resource(semaphore)
semaphore.singal() //is for releasing the resource(semaphore)

按以下方式更改代码。

var author: User? {

        print(1)
        var fetchedAuthor: User?
        let semaphore = DispatchSemaphore(value: 1)

        print(2)
        database.collection("users").document(authorId).getDocument { (document, error) in
            semaphore.wait()
            print(3)
            guard let user = document.flatMap({User(dictionary: $0.data())}) else {
                print("Could not get author: \(error.debugDescription)")
                return
            }

            fetchedAuthor = user
            semaphore.signal()
        }

        print(4)
        print(5)
        return fetchedAuthor
    }