Продолжайте выводить индекс из диапазона, и таблицы не будут отображаться правильно, возможно, из-за DispatchQueue - PullRequest
0 голосов
/ 30 апреля 2020

У меня настроено, так что каждый раз при изменении даты новые данные отображаются в виде таблицы. Мне нужно пару раз изменить даты, чтобы у меня что-то отображалось в таблицах, а затем оно начало корректно обновляться, но через некоторое время я продолжаю получать «ошибка индекса вне диапазона». Я подозреваю, что я не использую DispatchQueue должным образом. Что не так с моим кодом?

Спасибо

var showNumberOfRes: Int = 0

class HomeViewController:  UIViewController, UITableViewDelegate, UITableViewDataSource {


    @IBOutlet weak var tableView: UITableView!

    var restaurants = [Results]()     

    func todaysDate() -> String {

        let date = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let result = formatter.string(from: date)

        return result
    }

    @IBAction func datePicker(_ sender: UIDatePicker) {
        selectedDate = sender.date

    }

    var selectedDate : Date = Date() {
           didSet {
               let dateFormatter = DateFormatter()
               dateFormatter.locale = Locale(identifier: "es_ES_POSIX")
               dateFormatter.dateFormat = "yyyy-MM-dd"

             returnJson()

           }
       }

    func returnJson(){

        DispatchQueue.global(qos: .userInitiated).async {

            let formatter = DateFormatter()
           formatter.dateFormat = "yyyy-MM-dd"
            let dateSelected = formatter.string(from: self.selectedDate)

           let parameters = "{\n\t\"locale\": \”mainplace\”,\n\t\”date\": \"\(dateSelected)\",\n\t\"access_token\": \"\(token)\"\n}"
           let postData = parameters.data(using: .utf8)

           var request = URLRequest(url: URL(string: "https://somelink:18999/salesAPI/localeSales")!,timeoutInterval: Double.infinity)
           request.addValue("application/json", forHTTPHeaderField: "Content-Type")

           request.httpMethod = "POST"
           request.httpBody = postData

           let task = URLSession.shared.dataTask(with: request) { data, response, error in
               guard let data = data else {
                   print(String(describing: error))
                   return
               }
               print(String(data: data, encoding: .utf8)!)

               let decoder = JSONDecoder()

               if let jsonPetitions = try? decoder.decode(RootRequest.self, from: data) {
                   self.restaurants = jsonPetitions.results
                   showNumberOfRes = self.restaurants.count
                   print (" \(self.restaurants.count) got it from Json")

               }
               else {print("Nothing!!")}

        }

            task.resume()

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

            }

        }
    } // End Json

    func loadData() {
          tableView.reloadData()

        let defaults = UserDefaults.standard
         userNameData = defaults.string(forKey: "userNameData")!
         passwordData = defaults.string(forKey: "passwordData")!
         token = defaults.string(forKey: "enterKey")!

        returnJson()

               }

    override func viewDidLoad() {
        super.viewDidLoad()

         self.tableView.dataSource = self
         self.tableView.delegate = self

       returnJson()

    } // End of viewDidLoad

    // Starts Tables
    func numberOfSections(in tableView: UITableView) -> Int { return 1 }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        print("\(showNumberOfRes) printed in the table")
        return showNumberOfRes

    }

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

            let displayNames = restaurants[indexPath.row]

             cell.locales.text = displayNames.locale

             return cell

    }

    func tableView(_ tableView: UITableView,
                   heightForRowAt indexPath: IndexPath) -> CGFloat {

        return CGFloat(80)

    }  // End Tables


}

1 Ответ

0 голосов
/ 30 апреля 2020

Необходимо перезагрузить табличное представление внутри обработчик завершения задачи данных.

Два других изменения:

  1. Фоновая очередь избыточна как URLSession порождает собственную фоновую очередь
  2. Никогда try? в строке JSONDecoder. Поймай error и распечатай

    func returnJson() {
    
       let formatter = DateFormatter()
       formatter.dateFormat = "yyyy-MM-dd"
       let dateSelected = formatter.string(from: self.selectedDate)
    
       let parameters = "{\n\t\"locale\": \”mainplace\”,\n\t\”date\": \"\(dateSelected)\",\n\t\"access_token\": \"\(token)\"\n}"
       let postData = parameters.data(using: .utf8)
    
       var request = URLRequest(url: URL(string: "https://somelink:18999/salesAPI/localeSales")!,timeoutInterval: Double.infinity)
       request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    
       request.httpMethod = "POST"
       request.httpBody = postData
    
       let task = URLSession.shared.dataTask(with: request) { data, response, error in
           guard let data = data else {
               print(error!)
               return
           }
           print(String(data: data, encoding: .utf8)!)
    
           let decoder = JSONDecoder()
    
           do {
               let jsonPetitions = try decoder.decode(RootRequest.self, from: data) 
               self.restaurants = jsonPetitions.results
               showNumberOfRes = self.restaurants.count
               print (" \(self.restaurants.count) got it from Json")
               DispatchQueue.main.async {
                   self.tableView.reloadData()
               }
    
           } catch {
               print(error)
           }
       }
       task.resume()
    
    } // End Json
    
...