Swift Firestore获取文档ID [英] Swift Firestore Get Document ID

查看:63
本文介绍了Swift Firestore获取文档ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为数据库使用FirebaseFirestore.

I'm using FirebaseFirestore for my database.

我有一个包含名称和描述的列表数组.我还想获取每个列表的唯一documentId.这可能吗?

I have an array of Lists with a name and description. I'd also like to grab each lists unique documentId. Is this possible?

List.swift

List.swift

struct List {
    var name:String
    var description:String

    var dictionary:[String:Any] {
        return [
            "name":name,
            "description":description
        ]
    }
}

ListTableViewController.swift

ListTableViewController.swift

func getLists() {
    if Auth.auth().currentUser != nil {
        db.collection("lists").getDocuments { (querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                self.listArray = querySnapshot!.documents.flatMap({List(dictionary: $0.data())})
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

我发现您可以通过以下方式获取documentId

I found you can get the documentId by doing...

    for document in querySnapshot!.documents {
        print("\(document.documentID) => \(document.data())")
    }

但是如何将其存储在列表中以便以后调用?

But how do I store this in my List to be able to call later?

推荐答案

1.假设您正在快照中获取文档.

1.Suppose you are getting documents in snapshot.

    guard let documents = ducomentSnapshot?.documents else {
      print("Error fetching documents: \(error!)")
      return
   }

//使用此代码获取每个文档对象的documentId.

// Get documentId of each document objects using this code.

  for i in 0 ..< documents.count {
        let dictData = documents[i].data()
        let documentID = documents[i].documentID
        print("Document ID \(documentID)")
    }

这篇关于Swift Firestore获取文档ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆