0

I am trying to do a get request using the stackoverflow api using URLSession but i keep getting the following error:

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

override func viewDidLoad() {
    super.viewDidLoad()
    searchBar.delegate = self
    searchBar.sendsWholeSearchString = true

    if let url = URL(string: "https://api.stackexchange.com/docs/search#order=desc&sort=activity&intitle=swift&filter=default&site=stackoverflow") {
        var request = URLRequest(url: url)

        request.httpMethod = "GET"
        let dataTask = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            //handle response here
            if let error = error {
                print("Fuck! \(error.localizedDescription)")
                return
            }

            do {
                let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
                print(json)
            } catch {
                print(error.localizedDescription)
            }
        }
        dataTask.resume()
    }
}

I already have the url set to get swift results as if from a search so the url is "https://api.stackexchange.com/docs/search#order=desc&sort=activity&intitle=swift&filter=default&site=stackoverflow"

Also I read that the data is normally a gzip format but found that apparently URLSession automatically handles it ..

Any suggestions on where i am going wrong?

4
  • API is returning HTML instead of a JSON. You can verify this by printing as print(String.init(data: data!, encoding: .utf8)!). Commented Nov 5, 2019 at 6:33
  • @Kamran how can i make it return a json instead then? is the url i added wrong? Commented Nov 5, 2019 at 6:35
  • just enter your url in a webbrowser - the answer will surprise you ;) Commented Nov 5, 2019 at 6:35
  • You can not make it. Find a valid url that returns a JSON. Commented Nov 5, 2019 at 6:36

2 Answers 2

0

The correct url i was suppose to be using was https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=swift&site=stackoverflow

instead of

"https://api.stackexchange.com/docs/search#order=desc&sort=activity&intitle=swift&filter=default&site=stackoverflow"

Sign up to request clarification or add additional context in comments.

1 Comment

Yea! All set now
0

check it on postman this API returns HTML that's why you got HTML.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.