How to retrieve JSON data using NSURLSession in Swift?

I’m working on a Swift project in Xcode and need help fetching JSON data from a weather API. The API provider gave me some sample code using NSURLSession, but I’m having trouble getting the actual JSON response.

Here’s a simplified version of what I’m trying:

import Foundation

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

let url = URL(string: "https://weather-zipcode-api.example.com/forecast?zip=90210")!
var request = URLRequest(url: url)
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("Status code: \(httpResponse.statusCode)")
        // How do I get the JSON data here?
    }
}

task.resume()

I can see the response status code, but I’m not sure how to extract and parse the JSON data from the response. Any tips on how to do this properly? I’m new to working with APIs in Swift, so a beginner-friendly explanation would be really helpful. Thanks!

I’ve encountered this issue before. Here’s a straightforward approach to retrieve and parse JSON data using NSURLSession:

After your status code check, add the following code:

if let data = data {
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: ) as? [String: Any] {
print(jsonResult)
// Access specific values like this:
if let temperature = jsonResult[“temperature”] as? Double {
print(“Current temperature: (temperature)°F”)
}
}
} catch {
print(“Failed to parse JSON: (error.localizedDescription)”)
}
}

This code converts the raw data into a Swift dictionary, allowing you to access individual fields from your API response. Remember to handle potential errors and type-cast values appropriately for your specific API structure.

hey mate, i’ve dealt with this before. ur almost there! after the httpResponse check, add this:

if let data = data {
do {
let json = try JSONDecoder().decode(YourModelType.self, from: data)
print(json)
} catch {
print(“JSON error: (error)”)
}
}

replace YourModelType with ur actual model. this’ll parse the JSON into swift objects. good luck!

Hey there! I’ve been in your shoes before, and I can share what worked for me. In your code, you’re on the right track, but you’re missing a crucial step - actually handling the data you receive.

Here’s how I’d modify that completion handler:

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 json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            print(json)
            // Now you can work with your JSON data
        }
    } catch {
        print("Error parsing JSON: \(error)")
    }
}

This code checks for the data, then uses JSONSerialization to parse it into a Swift dictionary. From there, you can access specific fields in the JSON as needed for your app. Remember to handle errors and optionals properly in production code. Hope this helps!