0

Учусь создавать приложения для iOS. Приложение при запуске подтягивает json и выводит данные в таблицу. Проблема в том, что, насколько я понимаю, json подтягивается медленнее, чем выводится таблица, поэтому таблица появляется пустая. Пришлось перед выводом таблицы поставить паузу в 1 сек ( sleep(1) ). Работает нормально, но это ;е неправильный выход из положения. Подскажите как сделать правильно? Если можно, то поподробнее. Спасибо! )

class CurrencyTableViewController: UITableViewController {
    
    let imageName = ["1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png", "8.png", "9.png", "10.png", "11.png", "12.png", "13.png", "14.png", "15.png", "16.png", "17.png", "18.png", "19.png", "20.png", "21.png", "22.png", "23.png", "24.png", "25.png", "26.png", "27.png", "28.png", "29.png", "30.png", "31.png", "32.png", "33.png", "34.png"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getRates()
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        sleep(1)
        return currencyCharCode.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        assert(currencyCharCode.count == currencyNominal.count && currencyNominal.count == currencyName.count && currencyName.count == currencyValue.count)
        var currencies = [CurrencyStruct]()
        for index in 0..<currencyCharCode.count {
            currencies.append(CurrencyStruct(currencyCharCode: currencyCharCode[index], currencyNominal: currencyNominal[index], currencyName: currencyName[index], currencyValue: currencyValue[index], currencyDifference: currencyDifference[index]))
        }
        let sorting = currencies.sorted { item1, item2 in
            item1.currencyName < item2.currencyName
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "CurrencyViewCell", for: indexPath) as! CurrencyViewCell
        let name = imageName[indexPath.row]
        let image = UIImage(named: name)
        cell.imageView?.image = image
        cell.currencyCharCode.text = sorting[indexPath.row].currencyCharCode
        cell.currencyName.text = String("\(sorting[indexPath.row].currencyNominal) \(sorting[indexPath.row].currencyName)")
        cell.currencyValue.text = String("\(sorting[indexPath.row].currencyValue.roundTo)")
        if sorting[indexPath.row].currencyDifference > 0 {
            cell.currencyDifference.textColor = .green
            cell.currencyDifference.text = String("+\(sorting[indexPath.row].currencyDifference)")
        } else if sorting[indexPath.row].currencyDifference == 0 {
            cell.currencyDifference.textColor = .gray
            cell.currencyDifference.text = "0.0"
        } else {
            cell.currencyDifference.textColor = .red
            cell.currencyDifference.text = String(sorting[indexPath.row].currencyDifference)
        }
        return cell
    }
}

func getRates() {
    let urlString = "https://www.cbr-xml-daily.ru/daily_json.js"
    guard let url = URL(string: urlString) else {
        return
    }
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }
        guard error == nil else { return }
        do {
            let information = try JSONDecoder().decode(Information.self, from: data)
            let dateFormatterGet = DateFormatter()
            dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
            let dateFormatterPrint = DateFormatter()
            //            dateFormatterPrint.dateFormat = "dd.MM.yyyy, HH:mm"
            dateFormatterPrint.dateFormat = "dd.MM.yyyy"
            let date: Date? = dateFormatterGet.date(from: information.timestamp)
            timestamp = dateFormatterPrint.string(from: (date!))
            for currency in information.valute.values {
                let changes = (currency.value - currency.previous).roundTo
                currencyCharCode.append(currency.charCode)
                currencyNominal.append(currency.nominal)
                currencyName.append(currency.name)
                currencyValue.append(currency.value)
                currencyDifference.append(changes)
            }
        } catch let error {
            print(error)
        }
    }.resume()
}
2
  • у вас массив currencyCharCode как заполняется? Возможно он у вас не успевает заполниться до вызова методов таблицы, если имеет место асинхронный запрос
    – schmidt9
    1 сен 2021 в 8:13
  • Не совсем понял "как заполняется". Вот так: append(currency.charCode) Я добавил код парсинга json в массивы.
    – Dmitry
    1 сен 2021 в 9:06

2 ответа 2

1

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

override func viewDidLoad() {
    super.viewDidLoad()
    getRates {
       DispatchQueue.main.async { // fixed
           tableView.reloadData()
       }
    }
}

func getRates(_ completion: @escaping () -> Void) { // fixed
    let urlString = "https://www.cbr-xml-daily.ru/daily_json.js"
    guard let url = URL(string: urlString) else {
        return
    }
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }
        guard error == nil else { return }
        do {
            let information = try JSONDecoder().decode(Information.self, from: data)
            let dateFormatterGet = DateFormatter()
            dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
            let dateFormatterPrint = DateFormatter()
            //            dateFormatterPrint.dateFormat = "dd.MM.yyyy, HH:mm"
            dateFormatterPrint.dateFormat = "dd.MM.yyyy"
            let date: Date? = dateFormatterGet.date(from: information.timestamp)
            timestamp = dateFormatterPrint.string(from: (date!))
            for currency in information.valute.values {
                let changes = (currency.value - currency.previous).roundTo
                currencyCharCode.append(currency.charCode)
                currencyNominal.append(currency.nominal)
                currencyName.append(currency.name)
                currencyValue.append(currency.value)
                currencyDifference.append(changes)
            }
            
            completion()

        } catch let error {
            print(error)
        }
    }.resume()
}
4
  • Появилась ошибка: Escaping closure captures non-escaping parameter 'completeion' Пришлось сделать так: func getRates(_ completeion: @escaping() -> Void) И так: getRates { DispatchQueue.main.async { self.tableView.reloadData() } } Теперь работает! ) Вроде все правильно?
    – Dmitry
    1 сен 2021 в 14:19
  • Как же это все запомнить)
    – Dmitry
    1 сен 2021 в 14:22
  • В DispatchQueue.main нужно async или sync? И так и так работает.
    – Dmitry
    1 сен 2021 в 14:27
  • 1
    @Dmitry да исправления верные, пропустил эти моменты, нужно использовать async
    – schmidt9
    2 сен 2021 в 6:52
1

Вам нужно после получения данных и их обработки просто обновить таблицу через tableView.reloadData() А до этого момента показать, что идет процесс получения и обработки, например с помощью UIActivityIndicatorView.

2
  • Пытался обновлять tableView.reloadData() — все равно пустая таблица на выходе.
    – Dmitry
    1 сен 2021 в 7:52
  • Может не в том месте обновляю tableView.reloadData()? ))
    – Dmitry
    1 сен 2021 в 8:00

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.