ios - Swift 上的 "Fatal error: Unexpectedly found nil while unwrapping an Optional value"和 JSON

标签 ios json swift

我有一个问题,我不知道如何解决它,我有一个保存在变量中的 json,我想将它列在 TableView 中。到目前为止,我已经学会了如何通过下载 json 来做到这一点,但从未在本地下载。 我附上我的代码:

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(协议(protocol))

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)
        })
    }
}

详细JSON.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

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
    }

}

非常感谢您阅读我的问题并给予支持。

最佳答案

urlPath 应该是代表 URL 地址的 String ,而不是 JSON ! 所以这里: let url: URL = URL (string: urlPath)! 会因为 ! 而变得粗俗。它无法从 json 初始化 URL 并且您强制它。所以它会崩溃。

关于ios - Swift 上的 "Fatal error: Unexpectedly found nil while unwrapping an Optional value"和 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54644063/

相关文章:

ios - Firestore分页数据+快照监听器

ios - 应用程序崩溃 setObject ForKey : object cannot be nil

ios - 如何设置 AudioStreamBasicDescription 属性?

ios - 在 JSQMessagesViewController 中读取未读状态

java - 尝试在 Java 中将 List 从数据库转换为 json 时的 Stackoverflow

ios - 无法将类型 '(_) -> ()' 的值转换为预期的参数类型 '(() -> Void)?'

ios - 网络请求后 SwiftUI 更新 Elements.count

objective-c - 如何将 JSON 解析为 Objective C - SBJSON

javascript - 当 AngularJS 缓存 HTTP 请求时,它缓存解析的 JSON 对象还是字符串响应本身

swift - 如何对 Sprite 集合运行一个 Action ?