【发布时间】:2017-08-02 22:40:32
【问题描述】:
所以我正在使用天气 API: https://api.darksky.net/forecast/88d117d813f2014a1ce7f3de6a00c720/50.909698,-1.404351
我想要实现的是将每分钟的所有 precipIntensity 放入一个数组中。这样我可以制作一个图表,其中 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文件如下:
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 次。
- 如何获取此信息?
- 我怎样才能将它放入一个数组中以使其成为一个图表并继续我的工作?
提前致谢。
【问题讨论】:
-
您想要/需要使用
ObjectMapper吗?如果您正在考虑迁移到 swift 4,则可以改用Codable并删除ObjectMapper作为第三方依赖项 -
@nathan 我没听说过 Codable?上一个项目我使用 Object Mapper + Alomofire 从 API 获取数据,所以我认为这仍然是一个不错的方法。
-
更新了答案并修复了您的问题 + 2 个使用 Codable 的解决方案。如果您想了解有关 Codable/JSONEncoder/JSONDecoder 的更多信息,请查看带有相应标签的其他问题。很容易上手,因为简单的 JSON 结构只需要一行代码
标签: ios json swift alamofire objectmapper