I’m working on an iOS app in Swift and trying to fetch weather data from an API service. The API documentation gave me sample code that successfully connects and returns response headers, but I can’t figure out how to access the actual JSON data in the response body.
import Foundation
let apiHeaders = [
"x-rapidapi-host": "weather-data-service.p.rapidapi.com",
"x-rapidapi-key": "your-api-key-here"
]
let apiRequest = NSMutableURLRequest(url: NSURL(string: "https://weather-data-service.p.rapidapi.com/forecast?location=90210")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 15.0)
apiRequest.httpMethod = "GET"
apiRequest.allHTTPHeaderFields = apiHeaders
let urlSession = URLSession.shared
let task = urlSession.dataTask(with: apiRequest as URLRequest, completionHandler: { (responseData, urlResponse, requestError) -> Void in
if (requestError != nil) {
print(requestError)
} else {
let httpResp = urlResponse as? HTTPURLResponse
print(httpResp)
}
})
task.resume()
The code runs without errors and prints the HTTP response headers, but I need to parse the JSON content that comes back. I’m fairly new to iOS development and would appreciate guidance on extracting the response body data.
Your code’s almost there, but you’re ignoring the responseData parameter - that’s where your actual JSON lives. I hit this same wall when I started with URLSession. I’d get good response codes but couldn’t touch the data.
You need to handle responseData in your completion handler. Check for errors first, then make sure responseData exists and decode it with JSONSerialization. Try let jsonData = try JSONSerialization.jsonObject(with: responseData, options: .allowFragments). Wrap it in do-catch since JSON parsing throws errors.
One more thing - the completion handler runs on a background thread. If you’re updating UI with this weather data, dispatch back to main queue.
u missed the responseData param in your completion handler - that’s where the JSON will be. try to add JSONSerialization.jsonObject(with: responseData!, options: []) in the else block to parse it. also, cast it as dict or array, depending on what’s returned.
The responseData has your JSON payload. You’ll need to convert it properly with error checking. First, make sure there’s no request error, then check if responseData isn’t nil. Use JSONSerialization to turn the data into something Swift can work with. Try guard let data = responseData else { return } then let json = try JSONSerialization.jsonObject(with: data, options: []). Wrap the JSON parsing in do-catch since it throws exceptions. Once it’s parsed, cast the result as a dictionary or array based on what your API returns. Don’t forget to handle the async stuff properly if you’re updating UI elements.