I’m working on a Swift project in Xcode and need help getting JSON data from a weather API. I’ve set up the request using URLSession, but I’m only receiving the response headers. How can I retrieve the JSON content from the response body?
Here’s a simplified version of my code:
import Foundation
let headers = [
"api-host": "weather-forecast.myapi.com",
"api-key": "your-api-key-here"
]
let url = URL(string: "https://weather-forecast.myapi.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: \(httpResponse)")
}
}
task.resume()
I see the response headers but can’t figure out how to extract the JSON data. Any suggestions would be greatly appreciated!
hey mate, i’ve had similar issues before. try adding this to ur completion handler:
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: )
print(“JSON: (json)”)
} catch {
print(“Error parsing JSON: (error)”)
}
}
this shud help u get the actual json data. good luck!
In order to extract the JSON data from the API response, you need to process the data parameter provided in the completion handler. Instead of only printing the HTTP response, you should verify that data exists, and then attempt to parse it using JSONSerialization. For example, after checking for errors, use a guard statement to ensure that data is not nil. Then, within a do-catch block, parse the data into a JSON object (typically a dictionary) with the appropriate options. This way, you’ll gain access to the weather information in the JSON structure and can further manipulate it as needed.
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("JSON Data: \(jsonResult)")
// Process your JSON data here
}
} catch {
print("Error parsing JSON: \(error)")
}
}
This method not only confirms that the data is properly received, but also helps in safely decoding it to work with the actual weather details.
I’ve been down this road before, and I can tell you that working with URLSession can be tricky. One thing that helped me was using the Codable protocol instead of JSONSerialization. It’s more Swift-like and less error-prone.
First, create a struct that conforms to Codable and matches your JSON structure. Then, in your completion handler, use JSONDecoder to parse the data. Here’s a quick example:
struct WeatherForecast: Codable {
let temperature: Double
let description: String
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("Error: \(error?.localizedDescription ?? \"Unknown error\")")
return
}
do {
let decoder = JSONDecoder()
let forecast = try decoder.decode(WeatherForecast.self, from: data)
print("Temperature: \(forecast.temperature), Description: \(forecast.description)")
} catch {
print("Decoding error: \(error)")
}
}
task.resume()
This approach has saved me countless hours of debugging. Give it a shot and see if it works for you!