我在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”: “text / plain”},“draft”:false,“trigger”:{“time”:1497373512981.26, “@type”:“TimeTrigger”},“config”:{“name”:“Llego el cliente VIP Daniel“},”观众“:{”type“:”UserIds“,”ids“:[ “DGHCiwUTbDYnmSOOe7CwKKEB5SA2”,“FgLN69yCR1RzKY23fFdYhTD2HZg1”]}}
反响很好:
答案 0 :(得分:1)
问题很可能是request.httpBody=jsonPush() as? Data
方法问题jsonPush
返回String
,您直接将其转换为Data
,而不是使用data(using:)
request.httpBody = jsonPush().data(using: .utf8)
1}}用字符串来获取数据。
Public Name As Variant
Public Age As Variant