任何人都可以提供帮助,以便当用户单击客户名称(使用表视图)时,他们的详细信息将显示在第二个视图控制器(VC)上。我认为这是因为我还没有通过documentID来实现这一点。我尝试将documentID添加到Second VC .document(documentID)
初始VC代码
var customerList = [CustomerLsModel]()
override func viewDidLoad() {
super.viewDidLoad()
let db = Firestore.firestore()
db.collection("customers").getDocuments() { (snapshot, error) in
if let error = error{
print("Can't get customers: \(error)")
let alert = UIAlertController(title: "Error", message: "There was an issue in pulling your information. Please close the application and try again.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
} else {
for document in snapshot!.documents{
let firstname = document["firstname"]
let lastname = document["lastname"]
let address = document["address"]
let customer = CustomerLsModel(firstname: firstname as! String?, lastname: lastname as! String?, address: address as! String?)
self.customerList.append(customer)
self.orderAndLimit()
}
self.customerTable.reloadData()
}
}
}
}
第二个VC
let db = Firestore.firestore()
db.collection("customers").document().getDocument { (document, Error) in
if let document = document, document.exists{
self.firstNameLabel.text = document.get("firstname") as? String
}
}
这是我的客户模型课程
class CustomerLsModel{
var firstname: String!
var lastname: String?
var address: String?
init(firstname: String?, lastname: String?, address: String?){
self.firstname = firstname
self.lastname = lastname
self.address = address
}
答案 0 :(得分:0)
根据Swift的Firebase documentation,如果您使用不带路径参数的方法document()
,则将为新文档创建DocumentReference
。因此,当您尝试在此参考上使用getDocument
时-它为空。
仅当在参数中添加路径时,才会从现有文档中获取数据。
我希望它将对您有帮助!
答案 1 :(得分:-1)
答案实际上取决于您要如何处理数据,但这是两种方法。但是您的直觉是正确的-您需要跟踪客户的documentId。
因此,当您从Firestore中读取客户并传递所有字符串和documentId以填充每个对象时,您可以这样做
class CustomerLsModel{
var firstname: String!
var lastname: String?
var address: String?
var docId: String!
init(firstname: String?, lastname: String?, address: String?, docId: String) {
self.firstname = firstname
self.lastname = lastname
self.address = address
self.documentId = docId
}
}
或这样,通过传入Firestore快照使代码更简单
class CustomerLsModel {
var firstname: String?
var lastname: String?
var address: String?
var docId: String!
init(withDoc: QueryDocumentSnapshot) {
self.docId = withDoc.documentID
self.firstname = withDoc.get("first_name") as? String ?? "no first"
self.lastname = withDoc.get("last_name") as? String ?? "no last"
self.address = withDoc.get("addres") as? String ?? "no address"
}
}
从那里,当用户选择一个客户时,您可以将该对象传递到详细信息视图控制器以进行显示,也可以仅传递docId并将其用于子viewController中以从Firestore读取数据。
大约有100种“传递”数据的方法-Segue是一种流行的选择,您还可以在局部viewController中设置一个“ customer”变量,或者局部可以从主数据库读取数据。这真的取决于您的用例。