import UIKit import CryptoSwift final class FriendsViewController: UITableViewController { var friends: [User] = [] var imageCache = NSCache() init() { super.init(style: .grouped) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "Zabezpieczona wiadomość" let reuseIdentifier = String(describing: FriendCell.self) tableView.register( UINib(nibName: reuseIdentifier, bundle: nil), forCellReuseIdentifier: reuseIdentifier ) navigationItem.leftBarButtonItem = UIBarButtonItem( title: "Wyloguj się", style: .plain, target: self, action: #selector(signOut) ) friends = [ User(name: "Zakodowana1", email: "ukryty tekst1"), User(name: "Zakodowana2", email: "ukryty tekst2"), User(name: "Zakodowana3", email: "ukryty tekst3"), User(name: "Zakodowana4", email: "ukryty tekst4") ] } // MARK: - Actions @objc private func signOut() { try? AuthController.signOut() } override func numberOfSections(in tableView: UITableView) -> Int { return friends.isEmpty ? 1 : 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? 1 : friends.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 64 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Ja" : "Ukryte wiadomości" } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: FriendCell.self)) as? FriendCell else { fatalError() } let user = indexPath.section == 0 ? Settings.currentUser! : friends[indexPath.row] cell.nameLabel.text = user.name if let image = imageCache.object(forKey: user.email as NSString) { cell.avatarImageView.image = image } else { let emailHash = user.email.trimmingCharacters(in: .whitespacesAndNewlines) .lowercased() .sha1() if let url = URL(string: "https://www.gravatar.com/avatar/" + emailHash) { URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data, let image = UIImage(data: data) else { return } self.imageCache.setObject(image, forKey: user.email as NSString) DispatchQueue.main.async { self.tableView.reloadRows(at: [indexPath], with: .automatic) } }.resume() } } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }