2017-02-17 73 views
0

我有捲曲後,我想變成在迅速一個HTTP URL請求:形成捲曲後使用JSON數據作爲迅速HTTP 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"} 

我不知道如何形成它,因爲它是一個嵌套結構。

回答

1

斯威夫特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] 
+0

感謝您的回答。你知道我將如何形成一個像這樣的嵌套結構? 「通知」:{「body」:「你好」,「徽章」:「3」} – mjpablo23

+0

@ mjpablo23,添加到帖子 – Vahid

+0

非常感謝,我會嘗試一下 – mjpablo23