【问题标题】:Access A Value in Wunderground API在 Wunderground API 中访问值
【发布时间】:2015-08-11 18:58:59
【问题描述】:

我正在尝试将 Wunderground 整合到我当前的项目中。我看过几个 api 教程,但我似乎无法弄清楚如何访问 API 的某个部分。例如,这是 API 的样子:

{
   "response": {
   "version":"0.1",
   "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
   "features": {
      "history": 1
   }
   }
    ,
"history": {
    "date": {
    "pretty": "August 9, 2015",
    "year": "2015",
    "mon": "08",
    "mday": "09",
    "hour": "12",
    "min": "00",
    "tzname": "America/Los_Angeles"
    },

假设我只想从 API 返回小时。我该怎么做?

【问题讨论】:

  • 另外,我不想必须使用 SwiftyJSON,因为它对我的项目有不利影响。
  • 好奇:什么样的副作用?
  • 我收到分段错误 11
  • 另外,你试过什么?一旦 Wunderground 返回数据,您应该能够获取所需的 JSON 的任何部分......发布的 JSON 是从 API 返回的内容吗?请发布一些代码。

标签: swift wunderground


【解决方案1】:

一种不用框架解析 JSON 的方法:

typealias JSONdic = [String: AnyObject]

NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: nsUrl), queue: NSOperationQueue.mainQueue(), completionHandler: { (_, data, _) -> Void in
    if let data = data, json = data as? JSONdic, history = json["history"] as? JSONdic, hour = history["hour"] as? String {
    println(hour)
}

【讨论】:

  • 但是 Swift 不识别“json”
  • json 是变量名,是你从 Alamofire 或 NSURLConnection 在闭包中得到的数据。
  • 这两个我都没有。你能解释一下 NSURLConnection 吗?我对 API 和 JSON 完全陌生,不知道自己在做什么。
  • @ButtonMasterBot 扩展了示例。
猜你喜欢
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
相关资源
最近更新 更多