Daniel ORTIZ
Daniel ORTIZ

Reputation: 2520

String to data as JSON Swift3

im working with URLRequest in swift3. For consume a rest service I need add a body into URLResquest, for this I use this String:

 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
}

but when I try to send data

 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)")
            }

The response is:

{ error = "Bad Request"; "error_description" = "Could not parse JSON: No content to map due to end-of-input"; }

But if I try with the output:

{"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" }, "audience": { "type": "UserIds", "ids": [ "DGHCiwUTbDYnmSOOe7CwKKEB5SA2", "FgLN69yCR1RzKY23fFdYhTD2HZg1" ] } }

The response is good:

enter image description here

Upvotes: 0

Views: 129

Answers (1)

Nirav D
Nirav D

Reputation: 72420

The issue most probably on line request.httpBody=jsonPush() as? Data as of method jsonPush return String you are directly type casting it to to Data that is wrong instead of that use data(using:) with string to get data.

request.httpBody = jsonPush().data(using: .utf8)

Upvotes: 1

Related Questions