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

moiiocjp  于 2023-02-20  发布在  其他
关注(0)|答案(1)|浏览(133)

我有一个表视图,当我滑动并删除表视图单元格时,我需要Firebase中的数据也可以删除,我需要有文档ID,我如何才能获得该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("succses")
                   
                    
                }
                
            }
        }
        
    }
}
`

这是下一个视图控制器

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)
    }
}

我试着创建一个var documentID并试图获取文档id,但我一直没有弄清楚如何获取。

pwuypxnk

pwuypxnk1#

在解析数据时,可以获取文档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 adress = dictionary["adress"] as? String,
              let timeStamp = dictionary["timeStamp"] as? Date else {return nil}
        self.init(name: name, adress: adress, timeStamp: timeStamp, documentID: id)
    }
}

相关问题