Reputation: 3625
I'm new to swift and thus the question. I want to wrap my http calls into a function of this signature.
func httpPost()-> Any
This code works but how can I wrap this code in the functio signature I want.
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
Upvotes: 1
Views: 69
Reputation: 100541
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
Upvotes: 4