如何快速发出HTTP请求? (错误:在json上)

时间:2019-05-20 11:14:26

标签: ios swift http request

我在运行代码时出错。我需要代表从URL请求的我的数据的全部信息。 但这在我跑步时中断了。 我认为代码做得很好,但是我不知道为什么在运行应用程序时会中断。 威胁JSON时可能会出现一些错误。

此错误:

  

线程3:致命错误:展开一个可选值时意外发现nil

import Foundation

public class UnidadeCurricularManager{
private var ucs = [UnidadeCurricular]();


init(){        

    //URL

    let url = URL(string: "http://209.97.133.56/api/ucs")!
    let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjQ2Yjg2ZDNlZDI2Y2IwOGU2NDFhZTI3NjNmMWI0ZDEwODAwZWI0M2U4YjM5MThiMTQ0YmU5YWFjMzBhNGU1ZDdhMTI4ZjA1MDI2NGNkYWZhIn0.eyJhdWQiOiIyIiwianRpIjoiNDZiODZkM2VkMjZjYjA4ZTY0MWFlMjc2M2YxYjRkMTA4MDBlYjQzZThiMzkxOGIxNDRiZTlhYWMzMGE0ZTVkN2ExMjhmMDUwMjY0Y2RhZmEiLCJpYXQiOjE1NTgzNDQ1MDIsIm5iZiI6MTU1ODM0NDUwMiwiZXhwIjoxNTg5OTY2OTAyLCJzdWIiOiIzIiwic2NvcGVzIjpbXX0.LSsn172WUQqEzUf3wzq4lxgBL8pbKGqjJCpn0iEFPFQY6DhZCtcm4jHkqTC0FFMYrAA1n87LfdBeSvcdgWFsndD6MoKHFkZViqZXlUHDeyMmT-bVs2IrNSE9kGuaRQhz1rtys2KFbB2y4lq5w2BPhokPYvLc0nTwZ7oPTZKQlJkUi80PKDMP3LMUQpilc2cSE8FGe-d1UtMYUeseivwHcNee4knjfOUIsGl7_pV4knU6DYTWL8IMXfb3GjbBTagFRWfbjeqMMvtFVdZGfTxdeVoMqSgEQlA0W20GyJ3Ox4WuZAaODk4b7Q4cudR8vmPTSjvVU-IqB6_9wvtE3HUMEwiGazQRcmFtVqBYFPVIBHFWNBsWI2AbMxR_KSA6URzF-6qydj53yRqO41E88KQiWbHy29mb8BCoNvjR4gN9F97rE9j9Xpt-EsHK6QEqBOeoJixu8srDrgmYul4nWroRU6dQsFZjfZS4Vnm1LFF-ykOo0YVY08oRcV3LQTb8TsnS3RuQzlMifEhDajBPTsVyCyW9OkkTsi3N96E1VeRhyT0S08InczXeRV_K5BMdt7tvVAEMPoR4GCcHAR5e7924WVsbl9KmJ4ituf_FdCfBKdvcmErURIlCfZRELLC_8kNaT-04CG3Vj9_LrUb6eOcJrutawh60V_ITojWAxyF2LnQ"
    var request = URLRequest(url: url)
    request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.httpMethod = "GET"


    URLSession.shared.dataTask(with: request) { (data, response , error) in
        guard let data = data else {
            return
        }
        do {
            if let jsonDictionary = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any>
            {
                if let dataArray = jsonDictionary["data"] as? [[String:Any]] {
                    for data in dataArray {

                        let ucIdMapSiges = data["unidadeCurricularIdMapSiges"] as! Int
                        let ucNome = data["unidadeCurricularNome"] as! String
                        let ucSigla = data["unidadeCurricularAbreviatura"] as! String
                        let anoCurricularIdMapSiges = data["anoCurricularIdMapSiges"] as! Int
                        let periodoNome = data["unidadeCurricularAbreviatura"] as! String
                        let codigoEstudante = data["numeroEstudante"] as! String
                        let ects = data["numero_creditos"] as! Int


                        var uc = UnidadeCurricular (ucName: ucNome, ucSigla: ucSigla, ucIdMapSiges: ucIdMapSiges, anoCurricularIdMapSiges: anoCurricularIdMapSiges, periodoNome: periodoNome, codigoEstudante: codigoEstudante, ects: ects)

                        self.ucs.append(uc);
                    }
                }

            } else {
                print("bad json")
            }
        } catch let error as NSError {
            print(error)
        }

        }.resume()

}

func getUcs() -> Dictionary<String, [UnidadeCurricular]> {
    var listaOfUcs = [String : [UnidadeCurricular]]()

    for u in ucs{
        if listaOfUcs[String(u.anoCurricularIdMapSiges)] != nil {
            listaOfUcs[String(u.anoCurricularIdMapSiges)]!.append(u);
        } else {
            var ucName = [UnidadeCurricular]();
            ucName.append(u);
            listaOfUcs[String(u.anoCurricularIdMapSiges)] = ucName;
        }
    }
    return listaOfUcs;
}
}

2 个答案:

答案 0 :(得分:0)

这是因为您正在使用强制解包,所以尝试此代码会导致崩溃

 for data in dataArray {

                    let ucIdMapSiges = data["unidadeCurricularIdMapSiges"] as? Int ?? 0
                    let ucNome = data["unidadeCurricularNome"] as? String ?? ""
                    let ucSigla = data["unidadeCurricularAbreviatura"] as? String ?? ""
                    let anoCurricularIdMapSiges = data["anoCurricularIdMapSiges"] as? Int 0
                    let periodoNome = data["unidadeCurricularAbreviatura"] as String ?? ""
                    let codigoEstudante = data["numeroEstudante"] as String ?? ""
                    let ects = data["numero_creditos"] as? Int ?? 0


                    var uc = UnidadeCurricular (ucName: ucNome, ucSigla: ucSigla, ucIdMapSiges: ucIdMapSiges, anoCurricularIdMapSiges: anoCurricularIdMapSiges, periodoNome: periodoNome, codigoEstudante: codigoEstudante, ects: ects)

                    self.ucs.append(uc);
                }

作为参考,请检查这些答案

What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?

https://learnappmaking.com/found-nil-while-unwrapping-optional-value/

答案 1 :(得分:0)

您投射

let codigoEstudante = data["numeroEstudante"] as! String

但应该是

let codigoEstudante = data["numeroEstudante"] as! Int

更好的方法

do {
    let res = try JSONDecoder().decode(Root.self, from: data)
    print(res.data)

} catch  {
    print(error)
}

struct Root : Codable {
    let data:[Model]
}

struct Model : Codable {
    let unidadeCurricularIdMapSiges,anoCurricularIdMapSiges,numeroEstudante,numero_creditos:Int
    let unidadeCurricularNome,unidadeCurricularAbreviatura:String

}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let ff = UnidadeCurricularManager()

        ff.getData { (res) in
            print(res)
            // refresh the table here
        }

    }
}


public class UnidadeCurricularManager{

    func getData(completion:@esca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fBKdvcmErURIlCfZRELLC_8kNaT-04CG3Vj9_LrUb6eOcJrutawh60V_ITojWAxyF2LnQ"
        var request = URLRequest(url: url)
        request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.httpMethod = "GET"


        URLSession.shared.dataTask(with: request) { (data, response , error) in
            guard let data = data else {
                return
            }

         //   print(String(data:data,encoding: .utf8))

            do {
                let res = try JSONDecoder().decode(Root.self, from: data)
                let dic = Dictionary(grouping: res.data, by: { String($0.anoCurricularIdMapSiges) })
                completion(dic)

            } catch let error as NSError {
                print(error)
            }

            }.resume()

       }

}

struct Root : Codable {
    let data:[Model]
}

struct Model : Codable {
    let unidadeCurricularIdMapSiges,anoCurricularIdMapSiges,numeroEstudante,numero_creditos:Int
    let unidadeCurricularNome,unidadeCurricularAbreviatura:String

}