Отображение температуры в нескольких UITableViewCells - PullRequest
0 голосов
/ 16 марта 2020

У меня проблема с UITableViewCells

Я создал два класса UITableView. Теперь я хотел бы, чтобы это отображалось в TableView. В качестве данных я беру API погоды, который должен показывать мне температуру и минимальную температуру в двух разных UITableViewCellen

Однако в качестве ошибки я получаю строку 39:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

Вот мой полный код:

import UIKit
import Foundation

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!



    override func viewDidLoad() {
        super.viewDidLoad()
    }



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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
                     let minus: Double = 32.00
                               let session = URLSession.shared
                               let weatherURL = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=Ismaning&appid=2da51d7209b1151fc1bf22e761c88d4e")!
                               let dataTask = session.dataTask(with: weatherURL) {
                               (data: Data?, response: URLResponse?, error: Error?) in
                               if let error = error {
                               print("Error:\n\(error)")
                               } else {
                               if let data = data {
                               let dataString = String(data: data, encoding: String.Encoding.utf8)
                               print("All the weather data:\n\(dataString!)")
                               if let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
                                   if let mainDictionary = jsonObj.value(forKey: "main") as? NSDictionary {
                                    if var temperature = mainDictionary.value(forKey: "temp") {
                                                  temperature = (temperature as! Double - minus) / 1.8 / 10
                                                   DispatchQueue.main.async {
                                                        cell.aktuelleTemperatur.text = "\(temperature)°C"

                                                   }
                                               }

                                   } else {
                                       print("Error: unable to find temperature in dictionary")
                                   }
                                   } else {
                                   print("Error: unable to convert json data")
                                   }
                                   } else {
                                   print("Error: did not receive data")
                               }
                               }
                               }
                               dataTask.resume()

                    return cell
                }
                else if indexPath.row == 1 {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellNr2") as! CustomCellNr2
                     let minus: Double = 32.00
                               let session = URLSession.shared
                               let weatherURL = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=Ismaning&appid=2da51d7209b1151fc1bf22e761c88d4e")!
                               let dataTask = session.dataTask(with: weatherURL) {
                               (data: Data?, response: URLResponse?, error: Error?) in
                               if let error = error {
                               print("Error:\n\(error)")
                               } else {
                               if let data = data {
                               let dataString = String(data: data, encoding: String.Encoding.utf8)
                               print("All the weather data:\n\(dataString!)")
                               if let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
                                   if let mainDictionary = jsonObj.value(forKey: "main") as? NSDictionary {
                                               if let temperature = mainDictionary.value(forKey: "temp") {
                                                let temperature1: Double? = (temperature as! Double - minus) / 1.8 / 10
                                                   DispatchQueue.main.async {

                                                       cell.mindestTemperatur.text = String(format:"%.f", temperature1!) + "°C"

                                                   }
                                               }

                                   } else {
                                       print("Error: unable to find temperature in dictionary")
                                   }
                                   } else {
                                   print("Error: unable to convert json data")
                                   }
                                   } else {
                                   print("Error: did not receive data")
                               }
                               }
                               }
                               dataTask.resume()

                    return cell
                }
                else {
                    let cell: UITableViewCell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "thirdCustomCell")
                    //set the data here
                    return cell
                }
            }
        }

Может кто-нибудь помочь мне с проблемой?

Заранее спасибо

Ответы [ 2 ]

0 голосов
/ 16 марта 2020

Всегда создавайте необязательные переменные, чтобы приложение никогда не создавало sh во время приведения типов

if var temperature = temperature1 as? Double{
        temperature = (temperature - 10) / 1.8 / 10
    }
0 голосов
/ 16 марта 2020

Эта ошибка отображается для необязательных значений. Для их обработки мы используем

guard let temperature = (temperature as! Double - minus) / 1.8 / 10 else {return}

ИЛИ

if let temperature = (temperature as! Double - minus) / 1.8 / 10

Другой способ - проверить и передать значение, если оно пустое,

temperature = (temperature as! Double - minus) / 1.8 / 10 ?? 0.0
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...