You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Alamofire 4调用OpenWeather API请求适配问题求助

Fixing Alamofire.request.responseJSON for Alamofire 4.x

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 switch on response.result to explicitly handle .success and .failure cases. This replaces the old way of checking response.success or response.error.
  • Explicit request method: While GET is the default, specifying method: .get makes 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 pass nil when 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 your WeatherCondition model 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:13:29