How can I retrieve JSON data using NSURLSession in Swift?

I’m developing a weather app using Swift, but I’m having trouble obtaining the JSON information from the API response. Here is the alternative code I’ve tried:

import Foundation

let headers = [
    "api-host": "weather-zipcode-service.example.com",
    "api-key": "my_secret_key"
]

let requestURL = URL(string: "https://weather-zipcode-service.example.com/forecast?zipcode=90210")!
var request = URLRequest(url: requestURL)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
    } else if let httpResponse = response as? HTTPURLResponse {
        print("Response code: \(httpResponse.statusCode)")
    }
}

task.resume()

Although this code executes without error, it only returns the response headers. What changes should I make to capture the full JSON data from the response? I’m still learning to work with APIs in Swift and would really appreciate your guidance.

hey ryan, try checking the ‘data’ object in your completion. if data exists, do a JSONSerialization.jsonObject(with: data) and catch errors. hope that helps, lmk if u need more info

You’re on the right track with your code, Ryan. To retrieve the JSON data, you need to handle the ‘data’ parameter in your completion handler. Here’s a modification to your existing code:

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }
    
    guard let data = data else {
        print("No data received")
        return
    }
    
    do {
        if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            print(jsonResult)
            // Process your JSON data here
        }
    } catch {
        print("JSON parsing error: \(error)")
    }
}

task.resume()

This should parse the JSON data from the response. Remember to handle the data appropriately based on your API’s structure.

Hey Ryan, I’ve been in your shoes before. NSURLSession can be tricky at first. Here’s what worked for me:

Instead of using JSONSerialization, I found it easier to use Codable protocol. First, create a struct that matches your JSON structure. Then, use JSONDecoder to parse the data. Something like this:

struct WeatherData: Codable {
// Define your properties here
}

let decoder = JSONDecoder()

do {
let weatherData = try decoder.decode(WeatherData.self, from: data)
// Use weatherData here
} catch {
print(“Decoding error: (error)”)
}

This approach is more type-safe and less error-prone. It’s been a game-changer for me in handling API responses. Give it a shot and see if it simplifies things for you!