如何在Firebase数据库中获取文档ID

huangapple go评论60阅读模式
英文:

How to get the Document ID in Firebase Database

问题

我有一个表格视图,当我滑动并删除表格视图单元格时,我需要删除Firebase中的数据,为了实现这一点,我需要文档ID,我应该如何获取它,以便删除表格视图单元格和Firebase中的数据?

这是第一个视图控制器




import UIKit
import FirebaseDatabase
import Firebase
import Firestore
class TableViewController: UITableViewController {
    
    var db: Firestore!
    var employeeArray = [employee]()
    var employeeKey: String = ""
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        db = Firestore.firestore()
        loadData()
        checkForUpdates()
        
        
    }
    
      
    
    func loadData() {
        db.collection("employee").getDocuments() {
            querySnapshot, error in
            if let error = error {
                print("\(error.localizedDescription)")
            } else {
                self.employeeArray = querySnapshot!.documents.compactMap({employee(dictionary: $0.data())})
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
                
            }
        }
    }
    
    func checkForUpdates() {
        db.collection("employee").whereField("timeStamp", isGreaterThan: Date())
            .addSnapshotListener {
                querySnapshot, error in
                guard let snapshots = querySnapshot else {return}
                
                snapshots.documentChanges.forEach {
                    diff in
                    
                    if diff.type == .added {
                        self.employeeArray.append(employee(dictionary: diff.document.data())!)
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    }
                }
            }
        
    }
   
    func UID()  {
//        let postRef = Firestore.firestore().collection("employee")
//        postRef.getDocuments { (snapshot, error) in
//            if error != nil {
//                print("error")
//
//            } else {
//                if let snapshot = snapshot {
//                    for document in snapshot.documents {
//                        let data = document.data()
//                        self.employeeKey = document.documentID
//                        let newSource = employee(timeStamp: Date(), documentID: document.documentID)
//                        self.employeeArray.append(newSource)
//                        print(document.documentID)
//                    }
//                    self.tableView.reloadData()
//                }
//            }
//        }
      
        self.db.collection("employee").getDocuments() { (snapshot, err) in

           if let err = err {
               print("Error getting documents: \(err)")
           } else {
               for document in snapshot!.documents {

                 if document == document {
                  print(document.documentID)
                    }
                      }
           }
       }
    }
      
   
    
    @IBAction func addEmployee(_ sender: Any) {
        
        let composeAlert = UIAlertController(title: "Add Employee", message: "Add Employee", preferredStyle: .alert)
        
        composeAlert.addTextField { (textField: UITextField) in
            textField.placeholder = "Name"
        }
        
        composeAlert.addTextField { (textField: UITextField) in
            textField.placeholder = "Adress"
        }
        
        
        composeAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        
        composeAlert.addAction(UIAlertAction(title: "Add Employee", style: .default, handler: { (action: UIAlertAction) in
                let documentID = ""
                if let name = composeAlert.textFields?.first?.text,
                let adress = composeAlert.textFields?.last?.text {
                let newEmployee = employee(name: name, adress: adress, timeStamp: Date(), documentID: documentID)
                
                var ref: DocumentReference? = nil
                
                ref = self.db.collection("employee").addDocument(data: newEmployee.dictionary) {
                    error in
                    
                    if let error = error {
                        print("Error adding document: \(error.localizedDescription)")
                    } else {
                        print("Document added with ID: \(ref!.documentID)")
                    }
                }
            }
            
        }))
        
        self.present(composeAlert, animated: true, completion: nil)
        
        
    }
    
    
    // MARK: - Table view data source
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return employeeArray.count
        
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        
        let tweet1 = employeeArray[indexPath.row]
        cell.textLabel?.text = "\(tweet1.name) \(tweet1.adress)"
        cell.detailTextLabel?.text = "\(tweet1.timeStamp) "
        
        
        return cell
        
        
    }
    
    
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) async {
         
            print(UID())

    }
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
  
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == UITableViewCell.EditingStyle.delete) {
            
            db.collection("employee").document("UID").delete() { [self] err in
                if let err = err {
                    print("Error removing document: \(err)")
                } else {
                    print("success")
                   
                    
                }
                
            }
        }
        
    }
}
`

这是下一个视图控制器




import UIKit
import FirebaseDatabase
import Firebase
import Firestore
protocol DocumentSerializable {
    init?(dictionary: [String: Any])
}

struct employee {
    var name: String!
    var address: String!
    var timeStamp: Date
    var documentID: String!
    
    var dictionary: [String: Any] {
        return [
            "name": name!,
            "address": address!,
            "timeStamp": timeStamp,
            "documentID": documentID!,
        ]
    }
}

   
extension employee: DocumentSerializable {
    init?(dictionary: [String: Any]) {
        guard let name = dictionary["name"] as? String,
              let address = dictionary["address"] as? String,
              let documentID = dictionary["documentID"] as? String,
              let timeStamp = dictionary["timeStamp"] as? Date else { return nil }
        self.init(name: name, address: address, timeStamp: timeStamp, documentID: documentID)
    }
}

我尝试创建一个documentID变量并尝试获取文档ID,但我从未弄清楚如何获取。

英文:

I have a table view and when I swipe and delete the table view cell I need the data in Firebase to delete as well for that to be possible I need to have the document ID how can I get that so I can delete the table view cell and the data in Firebase?

this is the first view controller




import UIKit
import FirebaseDatabase
import Firebase
import Firestore
class TableViewController: UITableViewController {
    
    var db:Firestore!
    var employeeArray = [employee]()
    var employeeKey:String = ""
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        db = Firestore.firestore()
        loadData()
        checkForUpdates()
        
        
    }
    
      
    
    func loadData() {
        db.collection("employee").getDocuments() {
            querySnapshot, error in
            if let error = error {
                print("\(error.localizedDescription)")
            }else{
                self.employeeArray = querySnapshot!.documents.compactMap({employee(dictionary: $0.data())})
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
                
            }
        }
    }
    
    func checkForUpdates() {
        db.collection("employee").whereField("timeStamp", isGreaterThan: Date())
            .addSnapshotListener {
                querySnapshot, error in
                guard let snapshots = querySnapshot else {return}
                
                snapshots.documentChanges.forEach {
                    diff in
                    
                    if diff.type == .added {
                        self.employeeArray.append(employee(dictionary: diff.document.data())!)
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    }
                }
            }
        
    }
   
    func UID()  {
//        let postRef = Firestore.firestore().collection("employee")
//        postRef.getDocuments { (snapshot, error) in
//            if error != nil {
//                print("error")
//
//            } else {
//                if let snapshot = snapshot {
//                    for document in snapshot.documents {
//                        let data = document.data()
//                        self.employeeKey = document.documentID
//                        let newSource = employee(timeStamp: Date(), documentID: document.documentID)
//                        self.employeeArray.append(newSource)
//                        print(document.documentID)
//                    }
//                    self.tableView.reloadData()
//                }
//            }
//        }
      
        self.db.collection("employee").getDocuments() { (snapshot, err) in

           if let err = err {
               print("Error getting documents: \(err)")
           } else {
               for document in snapshot!.documents {

                 if document == document {
                  print(document.documentID)
                    }
                      }
           }
       }
    }
      
   
    
    @IBAction func addEmployee(_ sender: Any) {
        
        let composeAlert = UIAlertController(title: "Add Employee", message: "Add Employee", preferredStyle: .alert)
        
        composeAlert.addTextField { (textField:UITextField) in
            textField.placeholder = "Name"
        }
        
        composeAlert.addTextField { (textField:UITextField) in
            textField.placeholder = "Adress"
        }
        
        
        composeAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        
        composeAlert.addAction(UIAlertAction(title: "Add Employee", style: .default, handler: { (action:UIAlertAction) in
                let documentID = ""
                if let name = composeAlert.textFields?.first?.text,
                let adress = composeAlert.textFields?.last?.text {
                let newEmployee = employee(name: name, adress: adress,timeStamp: Date(), documentID: documentID)
                
                var ref:DocumentReference? = nil
                
                ref = self.db.collection("employee").addDocument(data: newEmployee.dictionary) {
                    error in
                    
                    if let error = error {
                        print("Error adding document: \(error.localizedDescription)")
                    }else{
                        print("Document added with ID: \(ref!.documentID)")
                    }
                }
            }
            
        }))
        
        self.present(composeAlert, animated: true, completion: nil)
        
        
    }
    
    
    // MARK: - Table view data source
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return employeeArray.count
        
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        
        let tweet1 = employeeArray[indexPath.row]
        cell.textLabel?.text = "\(tweet1.name) \(tweet1.adress)"
        cell .detailTextLabel?.text = "\(tweet1.timeStamp) "
        
        
        return cell
        
        
    }
    
    
    
    
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) async {
         
            print(UID())

    }
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
  
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == UITableViewCell.EditingStyle.delete) {
            
            db.collection("employee").document("UID").delete() { [self] err in
                if let err = err {
                    print("Error removing document: \(err)")
                } else {
                    print("succses")
                   
                    
                }
                
            }
        }
        
    }
}
`

This is the next view Controller


import UIKit
import FirebaseDatabase
import Firebase
import Firestore
protocol DocumentSeriziable {
    init?(dictionary:[String:Any])
}

struct employee {
    var name: String!
    var adress: String!
    var timeStamp: Date
    var documentID: String!
    
        var dictionary:[String : Any] {
        return[
            "name":name!,
            "adress":adress!,
            "timeStamp":timeStamp,
            "documentID": documentID!,
            
        ]
    }
    
}

   
extension employee : DocumentSeriziable {
    init?(dictionary: [String : Any]) {
        guard let name = dictionary["name"] as? String,
              let adress = dictionary["adress"] as? String,
              let documentID = dictionary["documentID"] as? String,
              let timeStamp = dictionary["timeStamp"] as? Date else {return nil}
        self.init(name: name, adress: adress, timeStamp: timeStamp, documentID: documentID)
    }
}

I tried making a var documentID and trying to get the document id but I never figured out how.

答案1

得分: 1

你在解析数据时可以获取文档的 documentID

self.employeeArray = querySnapshot!.documents.compactMap({employee(id: $0.documentID, dictionary: $0.data())})

documentID 不是 data() 的一部分,但它在数据库中用作键。

protocol DocumentSeriziable {
    init?(id: String, dictionary: [String: Any])
}

extension employee: DocumentSeriziable {
    init?(id: String, dictionary: [String: Any]) {
        guard let name = dictionary["name"] as? String,
              let address = dictionary["address"] as? String,
              let timeStamp = dictionary["timeStamp"] as? Date else { return nil }
        self.init(name: name, address: address, timeStamp: timeStamp, documentID: id)
    }
}
英文:

You can get document documentID while you parsing the data

self.employeeArray = querySnapshot!.documents.compactMap({employee(id: $0.documentID, dictionary: $0.data())})

documentID is not a part of the data() but it uses as a key in database.

protocol DocumentSeriziable {
    init?(id: String, dictionary:[String:Any])
}

extension employee : DocumentSeriziable {
    init?(id: String, dictionary: [String : Any]) {
        guard let name = dictionary["name"] as? String,
              let adress = dictionary["adress"] as? String,
              let timeStamp = dictionary["timeStamp"] as? Date else {return nil}
        self.init(name: name, adress: adress, timeStamp: timeStamp, documentID: id)
    }
}

huangapple
  • 本文由 发表于 2023年2月19日 01:56:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75495301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定