【问题标题】:Showing Temperature in multiple UITableViewCells在多个 UITableViewCells 中显示温度
【发布时间】:2020-06-27 15:49:29
【问题描述】:

我的 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
                }
            }
        }

谁能帮我解决这个问题?

提前谢谢你

【问题讨论】:

  • cellForRowAt 中运行异步任务是荒谬的。

标签: ios json swift uitableview request


【解决方案1】:

显示此错误是针对可选值的。 为了处理它们,我们使用

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

【讨论】:

  • 我尝试实现您的代码,但没有成功。它给了我错误'条件绑定的初始化程序必须具有可选类型,而不是'双''
  • @Shinox 您可能已经尝试了第三个,请使用 0.0 重试。
  • 然后他给了我一个黄色错误:```nil 合并运算符的左侧'??'具有非可选类型'Double',因此从不使用右侧```
  • 这是一个例外,现在您可能不会遇到致命错误。
  • 当我运行应用程序时,我再次出现致命错误:在隐式展开可选值时意外发现 nil:
【解决方案2】:

始终创建变量选项,以便应用在进行类型转换时永远不会崩溃

if var temperature = temperature1 as? Double{
        temperature = (temperature - 10) / 1.8 / 10
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2012-02-24
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多