[英]Retrieving json data from http request in swift
I'm new to swift and thus the question. 我是新手,因此是个问题。 I want to wrap my http calls into a function of this signature.
我想将我的http调用包装到此签名的函数中。
func httpPost()-> Any
This code works but how can I wrap this code in the functio signature I want. 该代码有效,但如何将其包装在所需的functio签名中。
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()
I want to return the json object as Any here 我想在这里将json对象返回为Any
You can't return a direct value in an asynchronous function until you block the thread which is a bad idea , so you want a completion 在阻塞线程之前,您不能在异步函数中返回直接值,这是一个坏主意,因此您需要完成
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()
}
To call 打电话
httpPost { (json,error) in
print(json)
}
also it's better to cast the json as [Any]
/ [String:Any]
for Array/ Dictionary response respectively 也最好将json分别转换为
[Any]
/ [String:Any]
以获得Array / Dictionary响应
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.