如何从Firebase获取文档ID?

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

How to get the document ID from firebase?

问题

以下是您要翻译的内容:

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 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 = "Address"
        }
        
        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 address = composeAlert.textFields?.last?.text {
                let newEmployee = employee(name: name, address: address, 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 employeeItem = employeeArray[indexPath.row]
        cell.textLabel?.text = "\(employeeItem.name) \(employeeItem.address)"
        cell.detailTextLabel?.text = "\(employeeItem.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())")
        }
    }
}

This is the second ViewController:

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

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

extension employee: DocumentSerializable {
    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)
    }
}

I've tried to get the Document Id a couple of different ways but none of them worked.

英文:

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

This is the second ViewController:

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

I've tried to get the Document Id a couple of different ways but none of them worked

答案1

得分: 0

struct employee 中添加 var documentID: String

self.init(documentID: id, name: name, adress: adress, timeStamp: timeStamp) 中使用:

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!")
            }
        }
    }
}
英文:

Add in struct employee var documentID: String
And in self.init(documentID: id, name: name, adress: adress, timeStamp: timeStamp) and use

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

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

发表评论

匿名网友

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

确定