Pierre Janineh
Pierre Janineh

Reputation: 702

String(data: theData, encoding: String.Encoding.utf8) returns nil

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.

Upvotes: 2

Views: 3055

Answers (1)

Pierre Janineh
Pierre Janineh

Reputation: 702

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

Upvotes: 2

Related Questions