swift3のURLRequestで作業しています。JSON Swift3としての文字列swift3
public func jsonPush() -> String {
let date = NSDate().addingTimeInterval(60)
let text: String =
"{" +
"\"action\": {" +
" \"content\": {" +
" \"default\": \"VIP\"" +
"}," +
"\"@type\": \"SendLocalMessageAction\"," +
" \"bgAlert\": { " +
" }, " +
" \"contentType\": \"text\\/plain\"" +
"}," +
"\"draft\": false, " +
"\"trigger\": { " +
"\"time\": "+"\(date.timeIntervalSince1970 * 1000)"+", " +
"\"@type\": \"TimeTrigger\" " +
"}, " +
"\"config\": { " +
"\"name\": \"Llego el cliente VIP Daniel\" " +
"}, " +
"\"audience\": { " +
"\"type\": \"UserIds\", " +
"\"ids\": [ " +
"\"DGHCiwUTbDYnmSOOe7CwKKEB5SA2\", " +
"\"FgLN69yCR1RzKY23fFdYhTD2HZg1\" " +
"] " +
" } " +
"} "
print("El json es:\(text) como valor final")
return text
}
が、私は、データに
var request = URLRequest(url: URL(string: uriNotifications + appId)!)
request.httpMethod = "POST"
request.addValue(autenticacion, forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
request.httpBody=jsonPush() as? Data
session.dataTask(with: request) { data, response, error in
print("Entered the completionHandler")
if(error != nil) {
print("error")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
// let posts = json["posts"] as? [[String: Any]] ?? []
print("Cantidad")
print(json)
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data!, encoding: .utf8)
print("raw response: \(responseString)")
}
を送信しようとすると、応答は次のとおりです:
私はURLResquestに体を追加する必要があるRESTサービス、このために私は、この文字列を使用するを消費するために{ error = "不良リクエスト"; "error_description" = "JSONを解析できませんでした:入力の終了によりマップするコンテンツがありません"; }
しかし、私は出力をしようとした場合:
{ "アクション":{ "内容":{ "デフォルト": "VIP"}、 "@タイプ": "SendLocalMessageAction" "time":1497373512981.26、 "@type": "TimeTrigger"}、 "config"、 " 「:{ "名前": "Llegoエルcliente VIP ダニエル"}、 "観客":{ "タイプ": "ユーザーID"、 "IDS":[ "DGHCiwUTbDYnmSOOe7CwKKEB5SA2"、 "FgLN69yCR1RzKY23fFdYhTD2HZg1"]}}
レスポンスが良いです:
なぜあなたは*手動* JSON文字列を作成するのではなくコレクション型を作成して 'JSONSerialization.dataを(使用してください:?。'次に、あなたが自由のためにも、 'Data'を取得 – vadian
Beacause、私は唯一の変更を必要とします1つのフィールド.... –