Firebase Cloudstoreから取得したcollection("users")のデータをtableviewに一覧で表示する為に以下の様なコードを作成致しました。
しかしながら、func takename内では想定通りに配列が取得できているのですが(print(self.tn)では)、実際にTableViewに反映させると配列の中身が["取得したデータ"]の一つしか取得できておりません。
非同期処理などについて一通り、リサーチしたのですが一向に解決できません。
どこを訂正すれば想定通りTableViewに反映されるのでしょうか?
解答よろしくお願い致します。
Swift
1import UIKit 2import Firebase 3import FirebaseAuth 4 5class CellsViewController: UIViewController , UITableViewDelegate, UITableViewDataSource { 6 7 var tn:[String] = ["取得したデータ"] 8 var tableView: UITableView! 9 10 func takename(){ 11 // Mainスレッド 12 Firestore.firestore().collection("users").getDocuments() { (querySnapshot, err) in 13 // Backgroundスレッド 14 if let err = err { 15 print("(err)") 16 } else { 17 for document in querySnapshot!.documents { 18 let sam:String = (document.documentID) 19 let numnum:[String] = sam.components(separatedBy: " ") 20 21 self.tn += numnum 22 } 23 print(self.tn) 24// →想定通りの配列がprintされる 25 26 // TableViewやその他UIの更新を行う場合はMainスレッドで行う必要がある為、以下でMainスレッドに戻す 27 DispatchQueue.main.async { 28// 実行時、下記に対してエラーが出ます。Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value 29 self.tableView.reloadData() 30 } 31 } 32 } 33 } 34 35 override func viewDidLoad() { 36 super.viewDidLoad() 37 38 takename() 39 } 40 41 override func didReceiveMemoryWarning() { 42 super.didReceiveMemoryWarning() 43 } 44 45 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 46// print(tn.count) →1 47 return tn.count 48 } 49 50 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 51 let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 52 53 cell.textLabel!.text = tn[indexPath.row] 54 55 return cell 56 } 57} 58
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/19 04:37
2019/08/19 04:38