2
session = URLSession(configuration: URLSessionConfiguration.default)
        let url = URL(string: "http://localhost:8080/menu?action=get_all")!
        let task = session.dataTask(with: url) { (data: Data?, urlResponse: URLResponse?, error: Error?) in
            if error == nil{
                if let theData = data{
                    print(String(data: theData, encoding: String.Encoding.utf8))
                    print("is main thread ? \(Thread.current.isMainThread)")
                }
            }
            self.session.finishTasksAndInvalidate()
        }
        task.resume()

I'm trying to get JSON String from my localhost server with a "GET" request using Swift.

For some reason this keeps returning nil. I tried using String(decoding: theData, as: UTF8.self), this returns the value with � characters.

The issue is for sure not from the server. I tested it on Postman and it's working great.

Pierre Janineh
  • 394
  • 2
  • 13
  • 3
    If `String(data: theData, encoding: .utf8)` returns `nil` then the data is not a valid UTF-8 sequence. – Martin R Mar 21 '19 at 18:44
  • @MartinR and how can I get the data as a String then? – Pierre Janineh Mar 21 '19 at 18:45
  • You seem to be getting data from the local server. _You_ should know the encoding used to encode the response. – Sweeper Mar 21 '19 at 18:47
  • 1
    What does the data contain? How is it encoded? What string do you expect? – `print(theData as NSData)` might help to investigate the issue. – Martin R Mar 21 '19 at 18:48
  • 1
    It seems the JSON sent by your server is improperly encoded in the first place. JSON *must* use UTF8 encoding and if it cannot be interpreted as a valid UTF8 sequence it means it's not valid JSON. Maybe you are missing some headers? e.g. `Accept: application/json`? I would start by trying to decode the result as `.ascii` to see it. – Sulthan Mar 21 '19 at 18:50
  • @Sulthan: That depends on which version of the JSON standard is used. Older standards allowed UTF-16 and UTF-32 (and JSONDecoder can handle it, compare https://stackoverflow.com/a/54936869/1187415). – Martin R Mar 21 '19 at 18:55
  • /thank you guys, used `response.setCharacterEncoding("UTF8");` on my HTTPServlet response. – Pierre Janineh Mar 21 '19 at 18:56
  • @MartinR Thanks for the info. I felt something like that had existed but a fast search did not reveal anything. – Sulthan Mar 21 '19 at 19:08

1 Answers1

2

thank you guys, used response.setCharacterEncoding("UTF8"); on my HTTPServlet response.

Pierre Janineh
  • 394
  • 2
  • 13