AlamofireObjectMapper导致nil

时间:2017-08-02 22:40:32

标签: ios json swift alamofire objectmapper

所以我正在使用天气API: https://api.darksky.net/forecast/88d117d813f2014a1ce7f3de6a00c720/50.909698,-1.404351

我想要实现的是将每分钟的所有CanyIntensity都变成一个数组。通过这种方式,我可以创建一个图形,其中Y是precipIntensity,X是array.count(使用此API计数最多为61)。

所以这是我在ViewController中的代码:

func downloadWeatherDetails(completed: DownloadComplete) {
    // Alamofire Download
    let currentWeatherURL = URL(string: WeatherURL)!
    Alamofire.request(currentWeatherURL).responseObject { (response: DataResponse<WeatherResponse>) in

        let Forecast = response.result.value
        if let minutelyForecast = Forecast?.minutelyForecast {
            for forecast in minutelyForecast {
                print(forecast.time)
                print(forecast.precipIntensity)
            }
        }

    }
}

我的班级文件如下:

class WeatherResponse: Mappable {
    var summary: String!
    var minutelyForecast: [Forecast]?

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        summary <- map["minutely.summary"]
        minutelyForecast <- map["minutely.data"]
    }
}

class Forecast: Mappable {
    var time: String!
    var precipIntensity: String!

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        time <- map["time"]
        precipIntensity <- map["precipIntensity"]
    }
}

然而,print(forecast.precipIntensity)打印出nil,61次。

  1. 我如何获得此信息?
  2. 如何将其放入数组中以使其成为图形并继续我的工作?
  3. 提前致谢。

1 个答案:

答案 0 :(得分:0)

您的代码存在的问题是timeprecipIntensity不是字符串值,而是数字。

class Forecast: Mappable {
    var time: Int!
    var precipIntensity: Double!
    ...
}

提取降水数据:

func downloadWeatherDetails(completed: DownloadComplete) {
    // Alamofire Download
    let currentWeatherURL = URL(string: WeatherURL)!
    Alamofire.request(currentWeatherURL).responseObject { (response: DataResponse<WeatherResponse>) in

        let Forecast = response.result.value
        if let minutelyForecast = Forecast?.minutelyForecast {
            // Data is already sorted from the API
            // but you could be sure nothing happened while decoding
            // by using `sorted()`
            let minutelyPrecipIntensity = minutelyForecast
                .sorted { $0.time < $1.time }
                .flatMap { $0.precipIntensity }
        }

    }
}

修改:删除了Codable回答