I’m having trouble setting up API calls in my Swift iOS project. I’m working on connecting to an external weather service but it doesn’t seem to work. Here’s my current code snippet:
import UIKit
class WeatherService {
func fetchWeatherData() {
let apiHeaders = [
"x-rapidapi-host": "weather-api-service.p.rapidapi.com",
"x-rapidapi-key": "YOUR_API_KEY_HERE"
]
guard let apiURL = URL(string: "https://weather-api-service.p.rapidapi.com/current?city=Paris%252Cfr") else {
return
}
var urlRequest = URLRequest(url: apiURL)
urlRequest.httpMethod = "GET"
urlRequest.allHTTPHeaderFields = apiHeaders
urlRequest.timeoutInterval = 15.0
let networkSession = URLSession.shared
let apiTask = networkSession.dataTask(with: urlRequest) { responseData, urlResponse, requestError in
if let error = requestError {
print("Network error: \(error)")
return
}
if let httpResp = urlResponse as? HTTPURLResponse {
print("Status code: \(httpResp.statusCode)")
}
}
apiTask.resume()
}
}
What’s the correct way to structure this code so it will function properly in a real application?