Сделать изображения базы данных изображений таблиц из JSON URL - PullRequest
0 голосов
/ 20 июня 2020

Я пытаюсь сделать изображения таблиц конкретным изображением профиля c человека, которое хранится в моей базе данных. У меня есть NSURL, который может распечатать список URL-адресов, но я не знаю, как добавить его в UIImage для каждого человека в своей ячейке. У меня есть код:

      import UIKit
      import Firebase

   class NetworkTableViewController: UITableViewController, UISearchBarDelegate {

var data = [String]()

var users = [User]()

let cellId = "cellId"

var filteredData: [String]!

@IBOutlet weak var searchBar: UISearchBar!

let searchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() {
    super.viewDidLoad()

    searchBar.delegate = self

    fetchUsers()

    filteredData = data

}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows

    return filteredData.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId)! as UITableViewCell

    let user = users[indexPath.row]

    cell.textLabel?.text = user.name

    cell.imageView?.image = UIImage(named: "Placeholder Photo")

    if let profileImageUrl = user.profileImageUrl {
        let url = NSURL(string: profileImageUrl)

        }

    return cell
}

//Mark: Search Bar Config
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filteredData = []


    if searchText == "" {
        filteredData = data

    }
    else {
        for fruit in data {

            if fruit.lowercased().contains(searchText.lowercased()) {

                filteredData.append(fruit)
            }
        }
    }
    self.tableView.reloadData()
}

func fetchUsers() {

    Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: String] {

            let user = User()


            user.name = dictionary["name"]
            user.email = dictionary["email"]
            user.facebookUrl = dictionary["facebookUrl"]
            user.instagramUrl = dictionary["instagramUrl"]
            user.linkedInUrl = dictionary["linkedInUrl"]
            user.profileImageUrl = dictionary["profileImageUrl"]
            user.twitterUrl = dictionary["twitterUrl"]

           // print(user.name!)

            self.users.append(user)
            self.data.append(user.name!)

            self.tableView.reloadData()

        }
    }, withCancel: nil)
   }
}

Учебное пособие, которое я смотрел, устарело, и я не знаю, что мне следует поместить здесь, чтобы назначить изображения правильным ячейкам таблицы.

1 Ответ

0 голосов
/ 20 июня 2020

Я рекомендую использовать Kingfisher . Его очень легко использовать.

Просто добавьте URL-адрес к просмотру изображения

let url = URL(string: "") // enter your URL string here
self.imageView.kf.setImage(with: url)

И не забудьте также обновить свой пользовательский интерфейс из основного потока

DispatchQueue.main.async {
  self.tableView.reloadData()
}
...