Alamofire 4 请求打开天气

Posted

技术标签:

【中文标题】Alamofire 4 请求打开天气【英文标题】:Alamofire 4 request to open weather 【发布时间】:2018-03-25 22:43:43 【问题描述】:

处理我的第一个 Alamofire 请求和更新到 Alamofire 4 的代码。无法正确更新此 Alamofire.request .responseJSON。我在看 Migration documentation: 但不够聪明。有什么建议吗?

    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 params = ["lat": lat, "lon": lon]

    //  Send the request
    Alamofire.request(url, method: .get, parameters: params)
        .responseJSON  request, response, result in
            switch result 
            case .Success(let json):
                let json = JSON(json)
                block(weatherCondition: self.createWeatherConditionFronJson(json))
            case .Failure(_, let error):
                print("Error: \(error)")
            
    

【问题讨论】:

【参考方案1】:

或许能帮到你

    Alamofire.request(url, method: .get, parameters: params, encoding: JSONEncoding.default).responseJSON  (response) in

        switch response.result 
       case .Success(let json):
            let json = JSON(json)
            block(weatherCondition: self.createWeatherConditionFronJson(json))
        case .Failure(_, let error):
            print("Error: \(error)")
        
    

【讨论】:

伟大的看起来更好。如果收到感谢@fidetro,我会去测试 :)【参考方案2】:
let APIKey = "YourApiKeyComesHere"

//  Sending the request to Open Weather
func retrieveCurrentWeatherAtLat(lat: CLLocationDegrees, lon: CLLocationDegrees,
                                 block: @escaping (_ weatherCondition: WeatherCondition) -> Void) 
    let url = "https://api.openweathermap.org/data/2.5/weather?APPID=\(APIKey)"
    let params = ["lat": lat, "lon": lon]
    print("Sending request... \(url)")
    let request = Alamofire.request(url, method: .get, parameters: params, encoding: URLEncoding(destination: .queryString)).responseJSON  (response) in
        print("Got response from server: \(response)")
        switch response.result 
        case .success(let json):
            let json = JSON(json)
            block(self.createWeatherConditionFronJson(json: json))
            print("Success: \(json)") //test
        case .failure(let error):
            print("Error: \(error)")
        
    
    request.resume()

【讨论】:

3 个小改动:.succes / .failure / block:@escaping 经过测试,现在它以纬度和经度为参数获取请求。

以上是关于Alamofire 4 请求打开天气的主要内容,如果未能解决你的问题,请参考以下文章

Alamofire 从多个请求中取消一个请求

AlamoFire 图像内存问题

发送 Alamofire JSON 数组 Swift

Alamofire RequestAdapter - 修改 URL

如何在 Swift 3 中使用 Alamofire 在 POST 请求中将给定的 JSON 作为参数发送?

Swift - 无法获取 Alamofire.request