1

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.

Grokify
  • 15,092
  • 6
  • 60
  • 81
junqili
  • 11
  • 2
  • 1
    Welcome to Stackoverflow. Please search. How to parse JSON is one of the most frequently asked questions. Here are many [related questions](https://stackoverflow.com/search?q=%5Bswift%5D+parse+json). – vadian Nov 22 '19 at 21:53

1 Answers1

0

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.

Pratham
  • 497
  • 3
  • 7