我已经做了一个api调用将产品添加到购物车。在按钮操作中我正在做这个api调用。我需要向api发送一些特定的参数。但是当我使用邮递员代码时。它在我的代码中抛出了很多错误:
func addtocartapicalling ()
{
let headers = [
"cache-control": "no-cache",
"postman-token": "4c933910-0da0-b199-257b-28fb0b5a89ec"
]
let postData = NSData(data: "{
"cartType" : "1",
"cartDetails" : {
"customerID" : "u",
"cartAmount" : "6999",
"cartShipping" : "1",
"cartTax1" : "69",
"cartTax2" : "",
"cartTax3" : "",
"cartCouponCode" : "",
"cartCouponAmount" : "",
"cartPaymentMethod" : "",
"cartProductItems" : {
"productID" : "9",
"productPrice" : "6999",
"productQuantity" : "1"
}
}
}".dataUsingEncoding(NSUTF8StringEncoding)!)
var request = NSMutableURLRequest(URL: NSURL(string: "http://api.php")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "POST"
request.allHTTPHeaderFields = headers
request.HTTPBody = postData
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
println(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
println(httpResponse)
}
})
dataTask.resume()
}
看到我上面的代码,有没有api调用。请帮帮我。
由于
let string = "{\"cartType" : "1" + "cartDetails" : { "customerID" : "u", + "cartAmount" : "6999", + "cartShipping" : "1", + "cartTax1" : "69", + "cartTax2" : "", + "cartTax3" : "", + "cartCouponCode" : "", + "cartCouponAmount" : "", + "cartPaymentMethod" : "",} + "cartProductItems" : { "productID" : "9", + "productPrice" : "6999", + "productQuantity" : "1" }" }"
答案 0 :(得分:1)
你不能只是从其他地方复制代码并期望它神奇地工作。主要问题是你不能在Swift中的多行上拆分文字字符串。将其放在一行中或在多行上添加多个文字字符串。例如......
let string = "{ \"cartProductItems\" : " +
"{\"productID\" : \"9\"," +
"\"productPrice\" : \"6999\"}}"
let postData = NSData(data: string.data(using: .utf8)!)
一旦您修复了大部分其他错误,您应该可以通过点击错误本身来修复,Xcode会为您修复项目NSURLSession has been renamed URLSession