我有一个curl帖子,我想在swift中变成一个http url请求:
curl post(命令行):
curl -X POST --header "Content-Type:application/json" --header "Authorization:key=SERVER_KEY" "https://gcm-http.googleapis.com/gcm/send" --data-ascii '{"to":"DEVICE_TOKEN","data":{"uid":"USER_ID"},"priority":10,"notification":{"body":"Hello","badge":"2"}}'
http请求(swift):
var request = URLRequest(url: URL(string: globalClass.getAppDelegate().global.sendUrl)!)
request.httpMethod = "POST"
var bodyData:String!
bodyData = "title=\(title)&body=\(message)&user_id=\(user_id)"
request.httpBody = bodyData.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request)
如何将数据部分放入http请求的bodyData?
"data":{"uid":"USER_ID"}
我不知道如何形成它,因为它是一个嵌套结构。
答案 0 :(得分:1)
Swift 2
转换为字典:
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
} catch {
print("Error")
}
将字典转换为JSON:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(serverKey, forHTTPHeaderField: "Authorization")
添加标题
"notification":{"body":"Hello","badge":"3"}
编辑:
将此JSON转换为Dictionary:
let notification = ["body": "Hello", "badge":"3"]
let data: [String: AnyObject] = ["notification": notification as AnyObject]
{{1}}