这里我使用这个Json函数从api获取数据但是在let task = URLSession.shared.dataTask(with: request) { data, response, error in
这行后它移动到最后一个大括号而不是在中间执行剩余的行,输出将是带有字典的数组,任何人都可以帮助我如何得到这个回应?
func shippingmethodURL(shippingMethodAPI:String) {
let url = NSURL(string: shippingMethodAPI)
var request = URLRequest(url: url! as URL)
request.httpMethod = "POST"
print(shippingMethodAPI)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let addtoCartVC = storyboard.instantiateViewController(withIdentifier: "checkout") as! CheckoutViewController
let parameters : [String: Any] = ["address":
[ "region": "California",
"region_code": "CA",
"region_id": "12",
"country_id": "US",
"company": "Test",
"telephone": "9492162752",
"postcode": "43",
"city": "Chennai",
"firstname": "gdfgdgdfg",
"lastname": "dgdfgdfgg",
"email": "sfdsfsdf@gmail.com",
"prefix": "",
"sameAsBilling": 1,
"street": ["Dsfdsfsd dfdsfdsf dsfsfdsfsf sdfsfdsfsdfC"]]]
print(parameters)
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
print(request)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let status = (response as! HTTPURLResponse).statusCode
self.keyStatusCode = status
print(status)
}
}
答案 0 :(得分:0)
当您使用dataTask方法时,您将获得一个任务对象。因此,您需要在其上调用resume()
。
创建任务后,必须通过调用resume()
方法启动它。该任务调用会话委托上的方法,为您提供响应元数据,响应数据等。