Неверное отображение изображений в TableView [Вопрос закрыт]
Как должно работать: Контроллер получает данные из Realm и передает значения в соответствующие поля строки (имя и изображение).
В чем проблема: При инициализации, функция cellForRowAt выполняется дважды, в результате чего изображения отображаются неверно. Не могу понять, почему происходит повторное выполнение. При выполнении программы с помощью брейкпоинтов ошибок не возникает.
Код контроллера:
class FavoriteTableVC: UITableViewController {
var data: Results<GetPhotoResults>?
private let networkService = NetworkService()
var token: NotificationToken?
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationItem.largeTitleDisplayMode = .automatic
navigationItem.title = TitlesIdentifiers.favoritePhotos.rawValue
tableView.register(FavoriteCell.self,
forCellReuseIdentifier: CellsIdentifiers.favoriteCell.rawValue)
pareTableAndRealm()
}
private func pareTableAndRealm() {
guard let realm = try? Realm() else { return }
self.data = realm.objects(GetPhotoResults.self)
token = data?.observe { [weak self] (changes: RealmCollectionChange) in
guard let tableView = self?.tableView else { return }
switch changes {
case .initial(_):
tableView.reloadData()
case let .update(_, deletions, insertions, modifications):
tableView.beginUpdates()
tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0) }), with: .automatic)
tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }), with: .automatic)
tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }), with: .automatic)
tableView.endUpdates()
case .error(let error):
print(error)
}
}
}
// MARK: - Table view Data Source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let count = data?.count else { return 0 }
return count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CellsIdentifiers.favoriteCell.rawValue, for: indexPath) as? FavoriteCell else { return UITableViewCell() }
guard let data = self.data else { return UITableViewCell() }
guard let name = data[indexPath.row].user?.name else { return UITableViewCell() }
guard let url = data[indexPath.row].urls?.small else { return UITableViewCell() }
cell.nameLabel.text = name
print(cell.nameLabel.text!)
if let url = URL(string: url) {
DispatchQueue.global().async {
AF.download(url, method: .get).responseData { response in
print("url: \(url)")
guard let data = response.value else { return }
let image = UIImage(data: data)
DispatchQueue.main.async {
cell.photoImageView.image = image
}
}
}
}
return cell
}
}
Сохранение данных в Realm:
class SaveDataInRealm {
static func saveData (_ data: GetPhotoResults) {
do {
var config = Realm.Configuration.defaultConfiguration
config.deleteRealmIfMigrationNeeded = true
let realm = try Realm(configuration: config)
realm.beginWrite()
realm.add(data, update: .modified)
try realm.commitWrite()
print(realm.configuration.fileURL!)
} catch {
print(error)
}
}
}
Вывод данных в консоль (количество строк в таблице - 4):
Ответы (1 шт):
Автор решения: Mikael
→ Ссылка
Проблема решена:
В методе pareTableAndRealm() в части
case .initial(_):
tableView.reloadData()
заменил tableView.reloadData() на функцию loadData().
private func loadData() {
do {
let realm = try Realm()
self.data = realm.objects(GetPhotoResults.self)
} catch {
print(error)
}
}
