0

I am trying to post some data to a server using Swift:

To create the JSON I do the following.

let json: [String: Any] = ["jwt": jwt as Any, "comment": newmessage as Any,"isuser": true,"ismax": false]

This seems to work as the debugger shows 4 key-value pairs listed below. I then try to serialize is using:

 let jsonData = try? JSONSerialization.data(withJSONObject: json)

This does not seem to work as the jsonData object logs to debugger as 0 bytes.

My send code is:

 let url = URL(string: "https://api-endpoint")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "No data")
                return
            }
            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
            if let responseJSON = responseJSON as? [String: Any] {
                print(responseJSON)
            }
        }

        task.resume()
    }

Although the compiler does not complain, in the debugger, I can see that jsonData has 0 bytes and the json does not appear to get sent.

What is wrong with my code:

Of note, the compiler forced me to cast some of the data as Any although I know they are strings. The json object appears in the debugger as:

(lldb) po json
▿ 4 elements
  ▿ 0 : 2 elements
    - key : "comment"
    ▿ value : Optional<String>
      - some : "Hi"
  ▿ 1 : 2 elements
    - key : "isuser"
    - value : true
  ▿ 2 : 2 elements
    - key : "ismax"
    - value : false
  ▿ 3 : 2 elements
    - key : "jwt"
    ▿ value : Optional<String>
      - some : "<-Long hash token ie string->"
user1904273
  • 4,562
  • 11
  • 45
  • 96
  • @user1904273 what is "jwt" and newmessage? Why you pass object as any rather then any primitive data type? – Chirag Shah Feb 22 '19 at 12:40
  • you mean let json: [String: Any]? The idea is that you can post a dictionary or something if needed in addition to a string – user1904273 Feb 22 '19 at 13:30
  • But from your **po** i can see that you only pass the string in all object not dictionary. – Chirag Shah Feb 22 '19 at 14:05
  • Before converting your dictionary to json check your dictionary with `isValidJSONObject`. this class method of `JSONSerialization`. for example in your case you need to check like this `if JSONSerialization.isValidJSONObject(json) { let jsonData = try? JSONSerialization.data(withJSONObject: json) }` – Chirag Shah Feb 22 '19 at 14:12

1 Answers1

-1
 let resultSerialization: AnyObject? = try JSONSerialization.jsonObject(with: dataResponse, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

 if (resultSerialization is [AnyHashable: Any]) == true 
{
    dictionaryResponse = resultSerialization as? NSMutableDictionary

 }
Dheeraj Kumar
  • 490
  • 3
  • 12