3

I am trying to make a script that sends data in the form of a json document in a POST request. To do this I am using the following code:

struct RequestModel: Codable {
    var api_key: String
    var service_code: String
    var description: String
    var media_url: String
    var attribute: [String: String]
    var long: String
    var lat: String

    init(api_key: String, service_code: String, lat: String, long: String, media_url: String, description: String, attribute: [String: String]) {
        ...
    }
}

class ClassName {
    func send(lat: Double, long: Double, comment: String, photoURL: String, photoID: String) {

        let sendReqeust = RequestModel(api_key: "123456789", service_code: "987654321", lat: lat, long: long, media_url: photoURL, description: comment, attribute: ["request_type":"example"])

        print("URL in function \(sendReqeust.media_url)")

        guard let uploadData = try? JSONEncoder().encode(sendReqeust) else {
            return
        }
        print(String(data: uploadData, encoding: .utf8)!)

        let url = URL(string: "http://example.com")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = uploadData

        var responseToken: String = ""

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            ...
        }
        task.resume()
    }   
}

The issue is with the mediaURL. When I encode the url it adds escape characters to the URL string.

The first print yields

https://example.com/

However the print after encoding yields:

https:\/\/example.com\/

How do I remove the escape characters from the url? The url does not properly resolve with the escape characters included.

  • I have tried adding it as part of the header but after testing on postman and in the app I have determined the url needs to be passed in via the request body.
  • I have tried setting up coding keys but that results in the url not being included when encoding.
  • I have tried passing in the URL as a URL type instead of String and it still doesn't work
A Israfil
  • 519
  • 4
  • 25
  • json_decode($string) – DrBorrow Aug 08 '19 at 23:08
  • Escaping slashes is perfectly valid, and it's the responsibility of the receiver to correctly parse this string value. Any self-respecting and standard-conforming JSON parser on the receiving end will do that, so you need to investigate what's going wrong there. – Gereon Aug 09 '19 at 05:18
  • @DrBorrow could you elaborate? – A Israfil Aug 12 '19 at 19:27
  • @Gereon unfortunately I do not own the server so I do not actually know how they parse their JSON – A Israfil Aug 12 '19 at 21:29

0 Answers0