Alamofire 4调用OpenWeather API请求适配问题求助
Hey there! I totally get where you're coming from—migrating to Alamofire 4 had me scratching my head over responseJSON changes too. Let's get your weather request sorted out.
First, the biggest shift in Alamofire 4 is how responseJSON handles success/failure: it now uses a Result enum instead of separate success/error properties in the response. You'll need to switch on this enum to handle both cases properly.
Here's the updated version of your retrieveCurrentWeatherAtLat function, with all the Alamofire 4 adjustments:
let APIKey = "myAPIkey" func retrieveCurrentWeatherAtLat(lat: CLLocationDegrees, lon: CLLocationDegrees, block: (_ weatherCondition: WeatherCondition?) -> Void) { let url = "http://api.openweathermap.org/data/2.5/weather?APPID=\(APIKey)" let parameters = ["lat": lat, "lon": lon] Alamofire.request(url, method: .get, parameters: parameters) .responseJSON { response in switch response.result { case .success(let jsonValue): // Parse the JSON response into your WeatherCondition model guard let weatherDict = jsonValue as? [String: Any], let condition = WeatherCondition(json: weatherDict) else { print("Failed to parse weather data from JSON") block(nil) // Pass nil or a default value to handle parsing failure return } block(condition) case .failure(let error): print("Weather request failed: \(error.localizedDescription)") block(nil) // Handle network/request errors appropriately } } }
Key changes to note:
- Result enum handling: We use a
switchonresponse.resultto explicitly handle.successand.failurecases. This replaces the old way of checkingresponse.successorresponse.error. - Explicit request method: While
GETis the default, specifyingmethod: .getmakes your code clearer and aligns with Alamofire 4's best practices. - Optional block parameter: I updated the block to accept
WeatherCondition?instead of a non-optional—this lets you passnilwhen the request or parsing fails, which is more robust than assuming success every time. - JSON parsing flow: We extract the raw JSON value from
.success(let jsonValue), cast it to a dictionary, then initialize yourWeatherConditionmodel from that dictionary.
A quick note: Make sure your WeatherCondition model has a way to initialize from a JSON dictionary (like a failable initializer init?(json: [String: Any]))—that's what we're using in the guard statement.
If you were relying on the old response.response or response.data properties, those are still available in the response parameter passed to the closure—you can access them just like before.
内容的提问来源于stack exchange,提问作者Patrik Rikama-Hinnenberg

