【发布时间】:2017-06-13 17:09:28
【问题描述】:
我正在使用 swift3 中的 URLRequest。 为了使用休息服务,我需要在 URLResquest 中添加一个主体,为此我使用这个字符串:
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)")
}
回复是:
{ error = "错误请求"; "error_description" = "无法解析 JSON:由于输入结束,没有要映射的内容"; }
但如果我尝试输出:
{"action": { "content": { "default": "VIP"},"@type": “SendLocalMessageAction”、“bgAlert”:{}、“contentType”: “文本/纯文本”},“草稿”:假,“触发器”:{“时间”:1497373512981.26, "@type": "TimeTrigger" }, "config": { "name": "Llego el cliente VIP 丹尼尔”},“观众”:{“type”:“UserIds”,“ids”:[ "DGHCiwUTbDYnmSOOe7CwKKEB5SA2", "FgLN69yCR1RzKY23fFdYhTD2HZg1" ] } }
反响不错:
【问题讨论】:
-
为什么要手动创建JSON字符串,而不是创建集合类型并使用
JSONSerialization.data(with:?然后你甚至可以免费获得Data。 -
因为,我只需要更改一个字段....