I’m working on a Swift project in Xcode and I’m trying to fetch weather data from an API. I’ve set up the NSURLSession and I can see the response headers, but I’m having trouble accessing the actual JSON data in the response body. Here’s a simplified version of my code:
import Foundation
let headers = [
"api-host": "weather-zipcode-service.example.com",
"api-key": "my_secret_key"
]
let url = URL(string: "https://weather-zipcode-service.example.com/forecast?zipcode=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("Response code: \(httpResponse.statusCode)")
// How do I access the JSON data here?
}
}
task.resume()
Can someone explain how I can parse and use the JSON data from the response body? I’m new to working with APIs in Swift, so any help would be appreciated!
hey grace, i’ve been there! heres a quick tip: after ur error check, add this:
if let data = data {
do {
let json = try JSONDecoder().decode(YourDecodableType.self, from: data)
// use json here
} catch {
print(“decode error: (error)”)
}
}
replace YourDecodableType with a struct matching ur JSON. hope this helps!
Your approach is sound, but you’re missing a crucial step. After checking for errors and the response code, you need to handle the ‘data’ parameter in your completion handler. Here’s how to modify your 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("Parsed JSON:", jsonResult)
// Now you can access specific fields in jsonResult
}
} catch {
print("JSON parsing error: \(error)")
}
}
task.resume()
This will parse the JSON data into a Swift dictionary. From there, you can access specific weather information as needed. Remember to handle potential errors and use optional binding when accessing dictionary values.
I’ve dealt with this exact issue before, and I can share what worked for me. In your code, you’re on the right track, but you need to handle the data parameter in your completion handler. Here’s how I typically parse JSON from an API response:
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
// Now you can work with your JSON data
print(json)
// Access specific values like this:
if let temperature = json["temperature"] as? Double {
print("Current temperature: \(temperature)°C")
}
}
} catch {
print("Error parsing JSON: \(error)")
}
}
This approach has always worked reliably for me. Just remember to import Foundation at the top of your file. Also, make sure you’re using the correct keys to access your JSON data - they should match the structure of the API response. Hope this helps!