有人能帮助我吗?我想返回从Firestore加载的所有数据的数组。
func loadData() {
var messages : [Message] = []
baseQuery().getDocuments() { (querySnapshot, error) in
if let error = error {
print("Error getting documents : \(error)")
}
else {
for document in querySnapshot!.documents {
var message : [String : Any]!
message = document.data()
let messageID : String = document.documentID
let sender : String = message["sender"] as! String
let subject : String = message["Subject"] as! String
let content : String = message["content"] as! String
let timeStamp : Date = message["Date"] as! Date
messages += [Message(messageID: messageID, sender: sender, subject: subject, content: content, timeStamp: timeStamp)]
}
}
}
}
答案 0 :(得分:0)
我得到了答案。我有两个答案,但我认为这个使用较少的CPU处理和内存。
func loadData(from collectionReference: DataCollectionReference, completion: @escaping ([Message]) -> Void){
reference(to: collectionReference).addSnapshotListener { (snapshot, error) in
if let error = error {
print("Error Retriving data: \(error.localizedDescription)")
return
}
guard let snapshot = snapshot else { return }
var messages = [Message]()
for document in snapshot.documents {
var dictionary = [String : Any]()
dictionary = document.data()
if let sender = dictionary["sender"], let content = dictionary["content"], let subject = dictionary["subject"] {
let message = Message(sender: sender as! String, subject: subject as! String, content: content as! String)
messages.append(message)
}
}
completion(messages)
}
}
并且在TableViewController上我做到了,它完美地运行了:
var messages = [Message]()
override func viewDidLoad() {
super.viewDidLoad()
FirestoreService.shared.loadData(from: .messages) { (messages) in
self.messages = messages
self.tableView.reloadData()
}
}