gpt4 book ai didi

ios - 如何在swift中发出http请求? (错误: on json)

转载 作者:行者123 更新时间:2023-11-29 05:45:14 25 4
gpt4 key购买 nike

我运行代码时出错。我需要表示从 URL 请求的数据的完整信息。但当我运行时,这会破裂。我认为代码做得很好,但我不知道为什么当我运行应用程序时会中断。威胁 JSON 时可能会出现一些错误。

此错误:

Thread 3: Fatal error: Unexpectedly found nil while unwrapping an Optional value

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

最佳答案

你施放

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:@escaping ([String:[Model]]) -> ()) {

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
}

// 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

}

关于ios - 如何在swift中发出http请求? (错误: on json),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com