Search code examples
iosswiftstringsingle-quotes

Single-quoted body in API request


I am making an iOS app that makes requests to an API. The request is in this format:

curl -X PUT -H "Content-Type: application/json" -d '{"username":"blabla@hotmail.com","password":"blabla"}' "https://server.mywebsite.com/login"

The API can only accept single-quoted strings in the body but I can't make a string with single quotes in Swift without it adding backslashes and making the string unreadable by the API.

"\'{\"email\": \"blabla@hotmail.com\", \"password\": \"blabla\"}\'"

Is there a way I can pass this string in Swift without the backslashes? Or is there a String or JSON encoding that is in that format?


Solution

  • The single quotes in your curl are required just in the Unix shell (to quote the double quotes on the command line), they are not actually transmitted to the server. The server just sees this JSON payload:

    {"username":"blabla@hotmail.com","password":"blabla"}
    

    So in your Swift API request you can remove the single quotes from your string:

    let auth = "{\"email\": \"blabla@hotmail.com\", \"password\": \"blabla\"}"
    

    Is there are way to avoid the escaping of the double-quotes here? No. In Swift you can't switch between ' and " like you can in say Python. Nor does it have """.

    Since it is easy to make quoting errors when building the JSON on your own, you may want to use JSONSerialization instead, like so:

    let jsonAuth   = [ "email":    "blabla@hotmail.com",
                       "password": "blabla" ]
    let jsonData   = JSONSerialization.data(withJSONObject: jsonAuth)
    let jsonString = String(data: data, encoding: .utf8)