Firebaseから文字列のデータを取得して、それを配列に格納し、カスタムセル上のUILabelに格納する処理を作ろうとしています。
当初は、ViewDidLoad内でデータを取得すれば、自然にカスタムセルで正常にデータが表示されると思っていました。
しかし、下記のコードで各処理の順番を出力したら、下記のような結果になりました。
↓
「結果」
1
2
4
6
3
3
5
どうしてviewDidLoad内にあるはずのloadNotification()(データを取得する関数)は、最初にスルーされて、後から実行されるのでしょうか?
データ取得が完了するまで次の処理には行かないようにするにはどうすればいいのでしょうか?
Swift
1 override func viewDidLoad() { 2 super.viewDidLoad() 3 4 print("1") 5 loadNotification() 6 print("6") 7 8 tableView.register(UINib(nibName: "NotificationCell", bundle: Bundle.main), forCellReuseIdentifier: "NotificationCell") 9 tableView.estimatedRowHeight = 65 10 tableView.rowHeight = 65 11 tableView.delegate = self 12 tableView.dataSource = self 13 } 14 15 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 16 print("5") 17 //セルの読みこみ 18 let cell = tableView.dequeueReusableCell(withIdentifier: "NotificationCell", for: indexPath) as! NotificationCell 19 //通知本文を表示 20 cell.message.text = notificationArray[indexPath.row]["message"]! 21 return cell 22 } 23 24 //お知らせを読み込む 25 func loadNotification() { 26 print("2") 27 //初期化 28 notificationArray = [[String:String]]() 29 //データベース参照 30 let ref = Database.database().reference(fromURL: "https://bookshare-b78b4.firebaseio.com/") 31 //データを取得 32 ref.child("Notification").child(userID).observe(.value) { (snap) in 33 for data in snap.children { 34 print("3") 35 let snapdata = data as! DataSnapshot 36 //辞書型に変換 37 let item = snapdata.value as! [String:String] 38 //配列に追加 39 self.notificationArray.append(item) 40 } 41 //tableViewを更新 42 self.tableView.reloadData() 43 } 44 print("4") 45 } 46
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/02/05 08:10
2019/02/05 08:49
2019/02/06 03:35