我有一个应用程序,你可以在其中添加一名员工,要添加一名员工,你按下添加按钮并输入所有信息,并且该数据存储在 Firestore 中,然后它获取输入的数据并获取姓名和地址并将其放入它在表视图单元格中,然后将其余数据存储在 Firestore 数据库中。我希望能够单击表格视图单元格,它会将您带到另一个显示所有员工数据的视图控制器。
这是第一个视图控制器
import Foundation
import UIKit
import FirebaseDatabase
import FirebaseCore
import Firebase
import Firestore
class TableViewController: UITableViewController {
var cell1 = ""
var db:Firestore!
var employeeArray = [Employee]()
var selectedData: String?
override func viewDidLoad() {
super.viewDidLoad()
db = Firestore.firestore()
loadData()
checkForUpdates()
}
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// let receiverVC = segue.destination as! DetailViewController
// receiverVC.isModalInPresentation = true
// receiverVC.name = cell1
//
// }
//
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()
}
}
}
}
}
@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.addTextField { (textField:UITextField) in
textField.placeholder = "Phone Number"
composeAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
composeAlert.addAction(UIAlertAction(title: "Add Employee", style: .default, handler: {_ in
if let name = composeAlert.textFields?.first?.text,
let adress = composeAlert.textFields?.last?.text,
let phoneNumber = composeAlert.textFields?.first?.text,
let documentID = composeAlert.textFields?.last?.text
{
let newEmployee = Employee(name: name, adress: adress, phoneNumber: phoneNumber,documentID: documentID)
var ref:DocumentReference? = nil
ref = self.db.collection("employee").addDocument(data: newEmployee.dictionary) { [self]
error in
if let error = error {
print("Error adding document: \(error.localizedDescription)")
}else{
loadData()
checkForUpdates()
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)"
cell.detailTextLabel?.text = "\(tweet1.adress)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) async {
// shouldPerformSegue(withIdentifier: "segueIdentifier", sender: nil)
let cell123 = employeeArray[indexPath.row]
}
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(employeeArray[indexPath.row].documentID).delete() { [self] err in
if let err = err {
print("Error removing document: \(err)")
} else {
loadData()
checkForUpdates()
}
}
}
}
}
这是第二个视图控制器
import Foundation
import UIKit
import Firebase
import Firestore
class DetailViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var adressLabel: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
var name: String?
var array = [Employee]()
override func viewDidLoad() {
super.viewDidLoad()
print("did print \(name)")
if let text = name {
nameLabel.text = text
}
}
}
这是第三个视图控制器
import Firebase
import Firestore
protocol DocumentSeriziable {
init?(id: String, xdictionary:[String:Any])
}
struct Employee {
var name: String
var adress: String
var phoneNumber:String
var documentID: String
// var timeStamp: Date
var dictionary:[String: Any] {
return[
"name":name,
"adress":adress,
"phoneNumber":phoneNumber,
//"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 phoneNumber = dictionary["phoneNumber"] as? String else {return nil}
//let timeStamp = dictionary["timeStamp"] as? Date else
self.init(name: name, adress: adress, phoneNumber: phoneNumber, documentID: id)
}
}
我尝试使用协议存根