gpt4 book ai didi

ios - 快速从http请求中检索json数据

转载 作者:搜寻专家 更新时间:2023-11-01 06:12:25 25 4
gpt4 key购买 nike

我是 swift 的新手,因此是这个问题的新手。我想将我的 http 调用包装到这个签名的函数中。

func httpPost()-> Any

此代码有效,但我如何将此代码包装在我想要的函数签名中。

let headers = [
"Content-Type": "application/json",
"cache-control": "no-cache"
]
let parameters = [
"client_id": "xxx",
"client_secret": "yyy"
] as [String : Any]

let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])

var request = URLRequest(url: URL(string: "http://xxx.xxx")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData

let session = URLSession.shared
let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in
guard let data = data else {return}
do{
try validate(response)
let json = try JSONSerialization.jsonObject(with: data, options: [])

}catch{
print(error)
}
//print(String(describing: data))
}

dataTask.resume()

我想在此处以 Any 形式返回 json 对象

最佳答案

在阻塞线程之前,您不能在异步函数中返回直接值,这是个坏主意,所以您需要完成

func httpPost(completion:@escaping(_ ret:Any?,err:Error?) -> Void)

let headers = [
"Content-Type": "application/json",
"cache-control": "no-cache"
]
let parameters = [
"client_id": "xxx",
"client_secret": "yyy"
] as [String : Any]

let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])

var request = URLRequest(url: URL(string: "http://xxx.xxx")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData

let session = URLSession.shared
let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in
guard let data = data else {
completion(nil,error)
return
}
do{
try validate(response)
let json = try JSONSerialization.jsonObject(with: data, options: [])
completion(json,nil)

}catch{
print(error)
completion(nil,error)
}
//print(String(describing: data))
}

dataTask.resume()
}

调用

httpPost { (json,error) in
print(json)
}

最好将 json 转换为 [Any]/[String:Any] 分别用于 Array/Dictionary 响应

关于ios - 快速从http请求中检索json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910406/

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