3

I am using the Stack Overflow API in Swift but keep getting an error:

The data couldn’t be read because it isn’t in the correct format.

whenever I try to use the JSON as shown in code below

func api(text: String){
    print(text)
    if let url = URL(string: "https://api.stackexchange.com/docs/search#order=desc&sort=activity&filter=default&site=stackoverflow") {
        var request = URLRequest(url: url)
        request.addValue("intitle", forHTTPHeaderField: text)
        request.httpMethod = "GET"
        print(request.description)
        let dataTask = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            //handle response here
            if let error = error {

                return
            }

            do {

                let json = try JSONSerialization.jsonObject(with: data!) as! [String: Any]
                print(json)

            } catch {
                print(error.localizedDescription)
            }
        }
        dataTask.resume()
    }
}

Any advice on what I'm doing wrong? I saw somewhere that the response was in GZip format so I tried using Alamofire because it should have some decompression for it, I thought, but still same issue.

2 Answers 2

0

First of all, you're using the documentation URL as endpoint, instead of the API endpoint, so you get HTML back, not JSON.

You can find the correct URL on that page, it's just below the parameters (hover over it to see the complete URL including the domain name):

enter image description here

Also, this line

request.addValue("intitle", forHTTPHeaderField: text)

is wrong; you can't add parameters like this. Since this API call is a GET operation, intitle needs to be part of the query (as shown in the screenshot above).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .