junqili
junqili

Reputation: 11

access json with the rapidapi provided nsurlsession

I'm trying to use this weather api https://rapidapi.com/interzoid/api/us-weather-by-zip-code/endpoints in my xcode project with swift. They provide me with the code

import Foundation

let headers = [
    "x-rapidapi-host": "us-weather-by-zip-code.p.rapidapi.com",
    "x-rapidapi-key": "my api key"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://us-weather-by-zip-code.p.rapidapi.com/getweatherzipcode?zip=11214")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error)
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse)
    }
})

dataTask.resume()

After running it I get the response headers but I wish to get the reponse body which is the json. I'm still pretty new to this and hope you can help.

Upvotes: 1

Views: 413

Answers (1)

Pratham
Pratham

Reputation: 547

You need to parse the response. The JSONSerialization class method jsonObject(with:options:) returns a value of type Any and throws an error if the data couldn’t be parsed.

let json = try? JSONSerialization.jsonObject(with: data, options: [])

Check out this question for more details: Correctly Parsing JSON in Swift 3

P.S. I'm not a Swift expert but here to help you.

Upvotes: 0

Related Questions