我无法从HTTPrequest返回数据,也无法使完成处理程序正常工作。因此,请协助我解决这个问题:
这是下面的代码:
var dictArr:[String:Any]!
func postAction(_ url:String, completion: @escaping(_ dict:[[String:Any]]) -> Void) {
guard let serviceUrl = URL(string: url) else { return }
let parameterDictionary: [String : Any] = [
"userId": "1",
"bookingType": "1",
"pageNumber": "1",
"filter": ""
]
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
print(parameterDictionary)
let postStr = self.getPostString(params: parameterDictionary)
let httpBody = postStr.data(using: .utf8)
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
print("response:--")
if let response = response {
print("response:--",response)
} else if let error = error {
print("error", error)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
self.dictArr = json as! [[String:Any]]
completion(self.dictArr)
} catch {
print(error)
}
}
}.resume()
}
func getPostString(params: [String : Any]) -> String {
var data = [String]()
for(key, value) in params{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
请尽快回复。