xcode 如何从firebase获取文档ID?

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

我有一个表视图,当我滑动并删除表视图单元格时,我需要同时删除Firebase中的数据,这样才有可能,我需要有文档ID,如何才能获得该ID,以便删除Firebase中的表视图单元格和数据?* 这是第一个ViewController

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(id: $0.documentID, xdictionary: $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 = querySnapshot!.documents.compactMap({employee(id: $0.documentID, xdictionary: $0.data())})
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    }
                }
            }
        
    }
   
    func UID()  {

        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
               
                if let name = composeAlert.textFields?.first?.text,
                let adress = composeAlert.textFields?.last?.text {
                let newEmployee = employee(name: name, adress: adress,timeStamp: Date())
                
                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())")
        }
        
    }
}

这是第二个视图控制器

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

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

extension employee : DocumentSeriziable {
    
    init?(id: String, xdictionary 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)
    }
}

我尝试了几种不同的方法获取文档ID,但都不起作用

6kkfgxo0

6kkfgxo01#

在结构体employee var documentID: String中添加,在init?(id: String, xdictionary dictionary: [String : Any]) { self.documentID = id中添加并使用

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCell.EditingStyle.delete) {
        db.collection("cities").document(employeeArray[indexPath.row].documentID).delete() { err in
            if let err = err {
                print("Error removing document: \(err)")
            } else {
                print("Document successfully removed!")
            }
        }
    }
}

相关问题