Ich arbeite mit URLRequest in swift3. einen Rest Service Für verbrauchen brauche ich einen Körper in URLResquest hinzufügen, für diese verwende ich diese Zeichenfolge:String zu Daten als JSON 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
}
aber wenn ich Daten versuchen, die Antwort
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)")
}
zu senden:
{ error = "Falsche Anfrage"; "error_description" = "JSON konnte nicht analysiert werden: Kein Inhalt aufgrund von Eingabe-Ende zuzuordnen"; }
Aber wenn ich mit dem Ausgang versuchen:
{ "Aktion": { "content": { "default": "VIP"}, "@ type": "SendLocalMessageAction" , "bgAlert": {}, "contentType": "text/plain"}, "Entwurf": false, "trigger": {"time": 1497373512981.26, "@type": "TimeTrigger"}, "config „: { "name": "Llego el cliente VIP Daniel"}, "Publikum": { "type": "UserIds", "ids": [ "DGHCiwUTbDYnmSOOe7CwKKEB5SA2", "FgLN69yCR1RzKY23fFdYhTD2HZg1"]}}
Die Antwort ist gut:
Warum erstellen Sie die Zeichenfolge JSON * manuell * anstatt eine Sammlung Art zu schaffen, und verwenden Sie 'JSONSerialization.data (mit:.' Dann erhalten Sie auch 'Data' kostenlos – vadian
Beacause ich nur ändern müssen ein Feld .... –