【发布时间】:2020-08-13 18:35:13
【问题描述】:
这是我的客户类别:
class Customer {
// Creating a customer
let name: String
let surname: String
let contactNo: String
let email: String
init(name: String,surname: String,contactNo: String,email: String) {
self.name = name
self.surname = surname
self.contactNo = contactNo
self.email = email
}
}
这是我正在使用的代码,它一直返回 nil:
class ProfileCus: UIViewController {
// Labels to display data
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var surnameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var contactLabel: UILabel!
// Reference to customer collection in Firestore
private var customerRefCollection = Firestore.firestore().collection("customers")
// Customer Object
private var customer = Customer(name: "a",surname: "a",contactNo: "a",email: "a")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
getDataFromFirebase{
self.customerRefCollection = Firestore.firestore().collection("customers")
print(self.customer,"debug step 5")
self.nameLabel.text = self.customer.name
self.surnameLabel.text = self.customer.surname
self.emailLabel.text = self.customer.email
self.contactLabel.text = self.customer.contactNo
}
}
func getDataFromFirebase(completion:@escaping() -> ()){
print(self.customer,"debug step 1")
let userID = Auth.auth().currentUser?.uid
print(userID,"debug step 2")
// Locate the user information on Firestore
customerRefCollection.document(userID!).getDocument { (snapshot, error) in
if let err = error {
debugPrint("Error fetching documents: \(err)")
}
else {
// Ensure that if there's nothing in the document that the function returns
guard let snap = snapshot else {return}
print(snap, "debug step 3")
// Parse the data to the customer model
let data = snap.data()
let name = data?["name"] as? String ?? ""
let surname = data?["surname"] as? String ?? ""
let email = data?["email"] as? String ?? ""
let contact = data?["contact no"] as? String ?? ""
// Create the customer and pass it to the global variable
let cus = Customer(name: name, surname: surname, contactNo: contact, email: email)
print(self.customer,"debug step 4")
self.customer = cus
}
completion()
}
}
}
谁能帮我理解我做错了什么,因为快照确实返回,但我解析数据的方式是错误的,因为客户对象返回 nil。
我添加了带有标签的打印语句,说明调试步骤 1 等,因此您可以跟踪运行时发生的情况,这是输出:
020-08-13 21:15:20.388052+0200 Clean Wheels[8599:430648] 6.29.0 - [Firebase/Analytics][I-ACS023012] 分析收集已启用
客户(姓名:“a”,姓:“a”,contactNo:“a”,电子邮件:“a”)调试步骤 1
可选(“RWVTDIUuL1eahOLpZT1UmMl0cja2”)调试步骤 2
在我看来,数据函数似乎不是正确使用的函数,因为当我对它显示在 UI 配置文件视图中的值进行硬编码时,是否有替代方法?
【问题讨论】:
-
请编辑问题以显示您尝试获取的文档,以及您在查询中使用的变量的值。您可能对查询做错了什么,但我们只是看不到那是什么。我建议还添加一些调试日志,以便我们可以看到代码是如何执行的。如果没有详细信息,您现在所拥有的就无法遵循。
-
@DougStevenson 我已经这样做了。请注意,我添加了一些带有调试步骤的打印语句,以帮助显示正在发生的事情。我希望我们能解决这个问题,好像我使用的数据函数一直返回 nil。
标签: ios swift google-cloud-firestore