简体   繁体   English

使用JSON的Swift上的“致命错误:在展开可选值时意外发现nil”

[英]“Fatal error: Unexpectedly found nil while unwrapping an Optional value” on Swift with JSON

I have a problem and I do not know how to solve it, I have a json that I keep in a variable and I would like to list it in a TableView. 我有一个问题,我不知道如何解决,我有一个保存在变量中的json,我想在TableView中列出它。 So far I have learned how to do it by downloading the json but never locally. 到目前为止,我已经学会了如何通过下载json来做到这一点,但从未在本地进行过。 I attach my code: 我附上我的代码:

CoreDataViewController.swift (here is my table) CoreDataViewController.swift(这是我的表)

import UIKit

class CoreDataViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, DatosModeloProtocol {

    var itemStruct: NSArray = NSArray()
    var selectPersona: DetalleJSON = DetalleJSON()
    @IBOutlet weak var listaTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

    self.listaTableView.delegate = self
    self.listaTableView.dataSource = self

    let datosModelo = DatosModelo()
    datosModelo.delegate = self
    datosModelo.downloadItems()


        // Do any additional setup after loading the view.
    }

    func itemsJSON(items: NSArray) {
        itemStruct = items
        self.listaTableView.reloadData()
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CoreDataTableViewCell
        let item: DetalleJSON = itemStruct[indexPath.row] as! DetalleJSON
      //  cell.lblID!.text = item.id
        cell.lblNombre!.text = item.nombre
        cell.lblAlias!.text = item.alias
        cell.lblFechaNac!.text = item.fechaNac
        cell.lblPosicion!.text = item.posicion

        return cell
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

DatosModelo.swift (the protocol) DatosModelo.swift(协议)

import UIKit
protocol DatosModeloProtocol: class{
    func itemsJSON (items: NSArray)
}

class DatosModelo: NSObject {

    weak var delegate: DatosModeloProtocol!

    let urlPath = "{
     "respuestas": [
            {
              "id": 1,
              "nombre": "Miguel Cervantes",
              "fechaNac": "8/Dic/1990",
              "posicion": "Desarrollador",
              "alias": "preg1"
            },
            {
              "id": 2,
              "nombre": "Juan Morales",
              "fechaNac": "03/Jul/1990",
              "posicion": "Diseñador",
              "alias": "preg2"
            },
            {
              "id": 3,
              "nombre": "Roberto Méndez",
              "fechaNac": "14/Dic/1990",
              "posicion": "Desarrollador",
              "alias": "preg3"
            },
            {
              "id": 4,
              "nombre": "Miguel Cuevas",
              "fechaNac": "08/Dic/1990",
              "posicion": "Programador",
              "alias": "preg4"
            }
      ]
}"

func downloadItems() {
        let url: URL = URL (string: urlPath)!
        let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
        let task = defaultSession.dataTask(with: url){
            (data, response, error) in
            if error != nil{
                print("Error al descargar datos")
            }else{
                print("Datos descargados")
                self.parseJSON(data!)
            }
        }
        task.resume()
    }


    func parseJSON(_ data:Data){
        var jsonResult = NSArray()
        do{
            jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
        }catch let error as NSError{
            print(error)
    }
    var jsonElement = NSDictionary()
    let detalles = NSMutableArray()
    for i in 0 ..< jsonResult.count
    {
        jsonElement = jsonResult[i] as! NSDictionary
        let detalle = DetalleJSON()
        let id = jsonElement["id"]
        let nombre = jsonElement["nombre"]
        let fechaNac = jsonElement["fechaNac"]
        let posicion = jsonElement["posicion"]
        let alias = jsonElement["alias"]

        detalle.id = id as? Int
        detalle.nombre = nombre as? String
        detalle.fechaNac = fechaNac as? String
        detalle.posicion = posicion as? String
        detalle.alias = alias as? String
        detalles.add(detalle)
        }
        DispatchQueue.main.async(execute: { () -> Void in
            self.delegate.itemsJSON(items: detalles)
        })
    }
}

DetalleJSON.swift DetalleJSON.swift

import UIKit

class DetalleJSON: NSObject {

    var id: Int?
    var nombre: String?
    var fechaNac: String?
    var posicion: String?
    var alias: String?

    override init() {

    }

    init(id: Int, nombre: String, fechaNac: String, posicion: String, alias: String){

        self.id = id
        self.nombre = nombre
        self.fechaNac = fechaNac
        self.posicion = posicion
        self.alias = alias
    }

    override var description: String{
        return "id: \(id), nombre: \(nombre), fechaNac: \(fechaNac), posicion: \(posicion), alias: \(alias)"
    }
}

CoreDataTableViewCell.swift CoreDataTableViewCell.swift

import UIKit

class CoreDataTableViewCell: UITableViewCell {

    @IBOutlet weak var lblNombre: UILabel!
    @IBOutlet weak var lblFechaNac: UILabel!
    @IBOutlet weak var lblID: UILabel!
    @IBOutlet weak var lblAlias: UILabel!
    @IBOutlet weak var lblPosicion: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

Thank you very much for reading my question, and for the support. 非常感谢您阅读我的问题并给予支持。

urlPath should be a String representing a URL address, not a JSON ! urlPath应该是代表URL地址的String ,而不是JSON So here: let url: URL = URL (string: urlPath)! 所以在这里: let url: URL = URL (string: urlPath)! will crass Because of the ! 会发疯的! . It can not initialize a URL from a json and you forced it. 它无法从json初始化URL ,因此您对其进行了强制。 So it will crash. 因此它将崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Swift:致命错误:在展开可选值时意外发现nil - Swift : fatal error: unexpectedly found nil while unwrapping an Optional value 快速致命错误:解开Optional值时意外发现nil - swift fatal error: unexpectedly found nil while unwrapping an Optional value Swift致命错误:解开Optional值时意外发现nil - Swift fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:在Swift 3中解开Optional值时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value in Swift 3 SWIFT-致命错误:解开可选值时意外发现nil - SWIFT - fatal error: unexpectedly found nil while unwrapping an Optional value Swift-致命错误:解开Optional值时意外发现nil - Swift - Fatal error: unexpectedly found nil while unwrapping an Optional values Swift中的可选类型错误:致命错误:解开可选值时意外发现nil - Optional type error in Swift: fatal error: unexpectedly found nil while unwrapping an Optional value Xcode Swift:appDelgate.window! is nil :致命错误:在解开可选值时意外发现 nil - Xcode Swift : appDelgate.window! is nil : Fatal error: Unexpectedly found nil while unwrapping an Optional value 致命错误:在Tableview中展开Optional值时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value in Tableview 致命错误:解开可选值(lldb)时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM