gpt4 book ai didi

ios - 如何在 swift 上发出带有身份验证的 http 请求?

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

IOS ucs

我需要发出带有身份验证的 http 请求。首先,我需要对以下 URL 进行 GET 操作: http://209.97.133.56/api/ucs但我需要通过身份验证来做到这一点。为此,我需要将以下标记放入某个 header 中

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjQ2Yjg2ZDNlZDI2Y2IwOGU2NDFhZTI3NjNmMWI0ZDEwODAwZWI0M2U4YjM5MThiMTQ0YmU5YWFjMzBhNGU1ZDdhMTI4ZjA1MDI2NGNkYWZhIn0.eyJhdWQiOiIyIiwianRpIjoiNDZiODZkM2VkMjZjYjA4ZTY0MWFlMjc2M2YxYjRkMTA4MDBlYjQzZThiMzkxOGIxNDRiZTlhYWMzMGE0ZTVkN2ExMjhmMDUwMjY0Y2RhZmEiLCJpYXQiOjE1NTgzNDQ1MDIsIm5iZiI6MTU1ODM0NDUwMiwiZXhwIjoxNTg5OTY2OTAyLCJzdWIiOiIzIiwic2NvcGVzIjpbXX0.LSsn172WUQqEzUf3wzq4lxgBL8pbKGqjJCpn0iEFPFQY6DhZCtcm4jHkqTC0FFMYrAA1n87LfdBeSvcdgWFsndD6MoKHFkZViqZXlUHDeyMmT-bVs2IrNSE9kGuaRQhz1rtys2KFbB2y4lq5w2BPhokPYvLc0nTwZ7oPTZKQlJkUi80PKDMP3LMUQpilc2cSE8FGe-d1UtMYUeseivwHcNee4knjfOUIsGl7_pV4knU6DYTWL8IMXfb3GjbBTagFRWfbjeqMMvtFVdZGfTxdeVoMqSgEQlA0W20GyJ3Ox4WuZAaODk4b7Q4cudR8vmPTSjvVU-IqB6_9wvtE3HUMEwiGazQRcmFtVqBYFPVIBHFWNBsWI2AbMxR_KSA6URzF-6qydj53yRqO41E88KQiWbHy29mb8BCoNvjR4gN9F97rE9j9Xpt-EsHK6QEqBOeoJixu8srDrgmYul4nWroRU6dQsFZjfZS4Vnm1LFF-ykOo0YVY08oRcV3LQTb8TsnS3RuQzlMifEhDajBPTsVyCyW9OkkTsi3N96E1VeRhyT0S08InczXeRV_K5BMdt7tvVAEMPoR4GCcHAR5e7924WVsbl9KmJ4ituf_FdCfBKdvcmErURIlCfZRELLC_8kNaT-04CG3Vj9_LrUb6eOcJrutawh60V_ITojWAxyF2LnQ

我来这里是为了寻求帮助,因为我做不到。

import Foundation

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


init(){

let json = "{ \"data\": [ { \"id\": \"201819S1911921391192161352\", \"unidadeCurricularId\": 18734, \"unidadeCurricularNome\": \"Algoritmos e Estruturas de Dados\", \"unidadeCurricularAbreviatura\": \"AED\", \"unidadeCurricularAtivo\": \"1\", \"unidadeCurricularIdMapSiges\": 9119213, \"anoCurricularId\": 3, \"anoCurricularNome\": \"2\", \"anoCurricularAtivo\": 1, \"anoCurricularIdMapSiges\": 2, \"periodoTempoId\": 5, \"periodoTempoNome\": \"1º Semestre\", \"periodoTempoAbreviatura\": \"1\", \"periodoTempoOrdem\": 1, \"periodoTempoAtivo\": 1, \"periodoTempoIdMapSiges\": \"S1\", \"numeroEstudante\": \"2140259\", \"idAnoLetivo\": 31, \"idUnidadeCurricular\": 18734, \"idEstadoInscricao\": 12, \"idAnoCurricular\": 3, \"numero_creditos\": 6 }, { \"id\": \"201819S1911921391192161352\", \"unidadeCurricularId\": 18735, \"unidadeCurricularNome\": \"Programação Avançada\", \"unidadeCurricularAbreviatura\": \"PA\", \"unidadeCurricularAtivo\": \"1\", \"unidadeCurricularIdMapSiges\": 9119213, \"anoCurricularId\": 3, \"anoCurricularNome\": \"2\", \"anoCurricularAtivo\": 1, \"anoCurricularIdMapSiges\": 2, \"periodoTempoId\": 5, \"periodoTempoNome\": \"1º Semestre\", \"periodoTempoAbreviatura\": \"1\", \"periodoTempoOrdem\": 1, \"periodoTempoAtivo\": 1, \"periodoTempoIdMapSiges\": \"S1\", \"numeroEstudante\": \"2140259\", \"idAnoLetivo\": 31, \"idUnidadeCurricular\": 18734, \"idEstadoInscricao\": 12, \"idAnoCurricular\": 3, \"numero_creditos\": 7 }, { \"id\": \"201819S1911921391192161352\", \"unidadeCurricularId\": 18735, \"unidadeCurricularNome\": \"Álgebra Linear\", \"unidadeCurricularAbreviatura\": \"AlgL\", \"unidadeCurricularAtivo\": \"1\", \"unidadeCurricularIdMapSiges\": 9119213, \"anoCurricularId\": 3, \"anoCurricularNome\": \"1\", \"anoCurricularAtivo\": 1, \"anoCurricularIdMapSiges\": 1, \"periodoTempoId\": 5, \"periodoTempoNome\": \"1º Semestre\", \"periodoTempoAbreviatura\": \"1\", \"periodoTempoOrdem\": 1, \"periodoTempoAtivo\": 1, \"periodoTempoIdMapSiges\": \"S1\", \"numeroEstudante\": \"2140259\", \"idAnoLetivo\": 31, \"idUnidadeCurricular\": 18734, \"idEstadoInscricao\": 12, \"idAnoCurricular\": 3, \"numero_creditos\": 7 } ] }";


//URL
let url = URL(string: "http://http://209.97.133.56/api/ucs")!

let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}

task.resume()


//JSON
guard let data = json.data(using: .utf8) 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)

ucs.append(uc);
}
}

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

}

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

}

最佳答案

在这里,您只需添加授权 header

使用Codable对于 JSON 解析,不要使用 JSONSerialization 并使用此 tool用于将 Json 转换为 struct

let url = URL(string: "http://209.97.133.56/api/ucs")!
let token = "your token"
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) ?? "Invalid JSON")
}.resume()

编辑

使用我给的工具将你的json转换为struct,工具转换后的JSON

struct UPS: Codable {
let data: [UPSData]

enum CodingKeys: String, CodingKey {
case data = "data"
}
}

struct UPSData: Codable {
let id: String
let unidadeCurricularID: Int
let unidadeCurricularNome: String
let unidadeCurricularAbreviatura: String
let unidadeCurricularAtivo: Int
let unidadeCurricularIDMapSiges: Int
let anoCurricularID: Int
let anoCurricularNome: String
let anoCurricularAbreviatura: String?
let anoCurricularAtivo: Int
let anoCurricularIDMapSiges: Int
let periodoTempoID: Int
let periodoTempoNome: String
let periodoTempoAvreviatura: String
let periodoTempoOrdem: Int
let periodoTempoAtivo: Int
let periodoTempoIDMapSiges: String
let numeroEstudante: Int
let idAnoLetivo: Int
let idUnidadeCurricular: Int
let idEstadoInscricao: Int
let idAnoCurricular: Int
let numeroCreditos: Int

enum CodingKeys: String, CodingKey {
case id = "id"
case unidadeCurricularID = "unidadeCurricularId"
case unidadeCurricularNome = "unidadeCurricularNome"
case unidadeCurricularAbreviatura = "unidadeCurricularAbreviatura"
case unidadeCurricularAtivo = "unidadeCurricularAtivo"
case unidadeCurricularIDMapSiges = "unidadeCurricularIdMapSiges"
case anoCurricularID = "anoCurricularId"
case anoCurricularNome = "anoCurricularNome"
case anoCurricularAbreviatura = "anoCurricularAbreviatura"
case anoCurricularAtivo = "anoCurricularAtivo"
case anoCurricularIDMapSiges = "anoCurricularIdMapSiges"
case periodoTempoID = "periodoTempoId"
case periodoTempoNome = "periodoTempoNome"
case periodoTempoAvreviatura = "periodoTempoAvreviatura"
case periodoTempoOrdem = "periodoTempoOrdem"
case periodoTempoAtivo = "periodoTempoAtivo"
case periodoTempoIDMapSiges = "periodoTempoIdMapSiges"
case numeroEstudante = "numeroEstudante"
case idAnoLetivo = "idAnoLetivo"
case idUnidadeCurricular = "idUnidadeCurricular"
case idEstadoInscricao = "idEstadoInscricao"
case idAnoCurricular = "idAnoCurricular"
case numeroCreditos = "numero_creditos"
}
}

在此类中添加所有网络请求代码

class NetworkRequest {


func auth<T: Decodable>(with url: URL, token: String, completion: @escaping (T) -> Void) {

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 {
completion(try JSONDecoder().decode(T.self, from: data))
} catch let error {
print(error)
}
}.resume()

}


}

在类里面的任何地方使用此代码

NetworkRequest().auth(with: url, token: token) { (ups: UPS) in
print("do what do want to you")
}

关于ios - 如何在 swift 上发出带有身份验证的 http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56218178/

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