形成卷曲邮政与 json 数据作为 swift httppost

标签: json URL Swift HTTP
发布时间: 2017/3/1 1:18:59
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有我想变成一个 http url 请求中的卷曲职务 swift :

卷曲邮政 (命令行)︰

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"}

我不知道如何形成它,因为它是一个嵌套的结构。

解决方法 1:

Swift 2

转换为字典︰

let title = "somthing"
let body = "body text"
let params = ["title":mail, "body": pass] as Dictionary<String, String>

转换为 JSON 的词典︰

do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
    } catch {
        print("Error")
    }

添加页眉

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(serverKey, forHTTPHeaderField: "Authorization")

编辑︰

这个 JSON 转换词典︰

"notification":{"body":"Hello","badge":"3"}

let notification = ["body": "Hello", "badge":"3"]
let data: [String: AnyObject] = ["notification": notification as AnyObject]
赞助商