【问题标题】:Parse twitter trend api results in swift快速解析 twitter 趋势 api 结果
【发布时间】:2016-10-26 17:40:00
【问题描述】:

我使用 twitter 趋势 api 来获取所有趋势的名称。

我有以下设置:

let url =  "\(APIConstants.Twitter.APIBaseURL)1.1/trends/place.json?id=1"

    let client = TWTRAPIClient()
    let statusesShowEndpoint = url
    let params = ["id": "20"]
    var clientError : NSError?

    let request = client.urlRequest(withMethod: "GET", url: statusesShowEndpoint, parameters: params, error: &clientError)

    client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
        if connectionError != nil {
            print("Error: \(connectionError)")
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: [])

        } catch let jsonError as NSError {
            print("json error: \(jsonError.localizedDescription)")
        }


    } 

调用后,json有如下数据:

(
{
    "as_of": "2012-08-24T23:25:43Z",
    "created_at": "2012-08-24T23:24:14Z",
    "locations": [
      {
        "name": "Worldwide",
        "woeid": 1
      }
    ],
    "trends": [
      {
        "tweet_volume": 3200,
        "events": null,
        "name": "#GanaPuntosSi",
        "promoted_content": null,
        "query": "%23GanaPuntosSi",
        "url": "http://twitter.com/search/?q=%23GanaPuntosSi"
      },
      {
        "tweet_volume": 4200,
        "events": null,
        "name": "#WordsThatDescribeMe",
        "promoted_content": null,
        "query": "%23WordsThatDescribeMe",
        "url": "http://twitter.com/search/?q=%23WordsThatDescribeMe"
      },

      {
        "tweet_volume": 2200,
        "events": null,
        "name": "Sweet Dreams",
        "promoted_content": null,
        "query": "%22Sweet%20Dreams%22",
        "url": "http://twitter.com/search/?q=%22Sweet%20Dreams%22"
      }
    ]
  }
)

根据上面的 json 数据,我想将所有 name 内的 trends 快​​速存储在一个数组中。

【问题讨论】:

    标签: json swift3 twitter-fabric


    【解决方案1】:

    您需要进行一些数据检查和转换,以确保以您期望的结构取回数据,然后从那里进行简单的迭代。这些方面的东西应该会让你继续前进:

    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any]
    var names = [String]()
    if let trends = json?["trends"] as? [[String:Any]] {
        for trend in trends {
            if let name = trend["name"] as? String {
                names.append(name)
            }
        }
    }
    

    注意各种as? 类型检查以安全地迭代结构。如需更深入地了解如何在 Swift 中干净地使用 JSON,包括将数据读入类型安全的结构,请查看this official blog post from Apple

    【讨论】:

      猜你喜欢
      • 2016-12-16
      • 2023-04-01
      • 2013-04-12
      • 2016-03-29
      • 2014-09-17
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多