Swift Firebase UITableViewCell загружается до того, как станут доступными данные для заполнения ячейки - PullRequest
0 голосов
/ 19 марта 2019

Я отправляю данные, представляющие собой массив строк, в контроллер таблиц.Эти строки являются "uid's", которые являются пользователями в моей базе данных.С помощью этого массива я вызываю firebase для извлечения всех пользователей, а затем сопоставляю uid.Я получаю правильные данные, но я распечатываю все, чтобы убедиться, что данные доступны, и данные доступны только после загрузки ячейки табличного представления, что приводит к тому, что данные равны нулю, вызывая сбой или просто пустые данные.Как я могу сделать загрузку данных сначала, а затем ячейку, чтобы данные были доступны для отображения?

Я создал функции для данных, и теперь у меня есть это в моем viewDidLoad.Кроме того, вы увидите, что я пытался добавить вызов firebase в настройку Cell, но, конечно, это не работает.

Массив строк

var data = [String]() 

viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    Database.database().reference().child("Businesses").observe(.value, with: { snapshot in
        if snapshot.exists() {
            self.businessUID = snapshot.value as? NSDictionary
            if let dict = snapshot.value as? NSDictionary {
                for item in dict {
                    let json = JSON(item.value)
                    let businessUid = json["uid"].stringValue
                    for uid in self.data {
                        if uid == businessUid {
                            let customerValue = self.businessUID?[uid]
                            self.businessDictionary = customerValue as! NSDictionary
                            print(self.businessDictionary)
                            print("Just printed the business dictionary")
                        }
                    }
                }
            }
        } else {
            print("does not exist")
        }
    })
}

Ячейка таблицы просмотра

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomerViewsSelectedBusinessesCell

    print(self.businessDictionary)
    print("Print the dictionary here to check the values")
    let businessValues = self.businessDictionary
    let uid = self.data.description

    print(businessValues)
    print("printed the business values")

    if let dict = businessValues {
        for item in dict {
            let json = JSON(item.value)
            let businessUid = json["uid"].stringValue
            for uid in self.data {
                if uid == businessUid {
                    let customerValue = self.businessUID?[uid]
                    self.businessData = customerValue as? NSDictionary
                    print(self.businessData)
                    print("Printing matching the uid values")
                }
            }
        }
    }

    cell.businessName.text = businessData?["businessName"] as? String
    cell.businessStreet.text = businessData?["businessStreet"] as? String
    cell.businessCity.text = businessData?["businessCity"] as? String
    cell.businessState.text = businessData?["businessState"] as? String

    let businessProfilePicture = businessData?["profPicString"] as? String
    if (businessProfilePicture!.characters.count) > 0 {
        let url = URL(string: (businessProfilePicture!))
            DispatchQueue.global().async {
                let data = try? Data(contentsOf: url!)
                DispatchQueue.main.async {
                    let image = UIImage(data: data!)?.potter_circle
                    cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
                    cell.profileImage.image = image
                    }
                }
            } else {
        let image = UIImage(named: "default")?.potter_circle
        cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
        cell.profileImage.image = image
    }

    return cell
}

1 Ответ

0 голосов
/ 19 марта 2019

Вот мое решение. Получил это на работу. Добавлен и использован «usersArray» для получения и отображения данных.

var data = [String]()
var usersArray = [NSDictionary?]()


override func viewDidLoad() {
    super.viewDidLoad()

    Database.database().reference().child("Businesses").observe(.value, with: { snapshot in
        if snapshot.exists() {
            self.businessUID = snapshot.value as? NSDictionary
            if let dict = snapshot.value as? NSDictionary {
                for item in dict {
                    let json = JSON(item.value)
                    let businessUid = json["uid"].stringValue
                    for uid in self.data {
                        if uid == businessUid {
                            let customerValue = self.businessUID?[uid]
                            self.usersArray.append(customerValue as! NSDictionary)
                            self.followUsersTableView.reloadData()
                        }
                    }
                }
            }
        } else {
            print("does not exist")
        }
    })
}


override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.usersArray.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomerViewsSelectedBusinessesCell

    let user : NSDictionary?

    user = self.usersArray[indexPath.row]

    cell.businessName.text = String(user?["businessName"] as! String)
    cell.businessStreet.text = String(user?["businessStreet"] as! String)
    cell.businessCity.text = String(user?["businessCity"] as! String)
    cell.businessState.text = String(user?["businessState"] as! String)

    let businessProfilePicture = String(user?["profPicString"] as! String)
    if (businessProfilePicture.characters.count) > 0 {
        let url = URL(string: (businessProfilePicture))
            DispatchQueue.global().async {
                let data = try? Data(contentsOf: url!)
                DispatchQueue.main.async {
                    let image = UIImage(data: data!)?.potter_circle
                    cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
                    cell.profileImage.image = image
                    }
                }
            } else {
        let image = UIImage(named: "default")?.potter_circle
        cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
        cell.profileImage.image = image
    }

    return cell
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...