-1

I using twitter trend api to get the name of all the trends.

I have the following setup:

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)")
        }


    } 

and after the call, json has the following data:

(
{
    "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"
      }
    ]
  }
)

From the above json data, i want to store all the name inside trends in an array in swift.

1 Answers1

0

There is some data checking and casting you need to do to make sure you're getting back the data in the structure you'd expect, and then from there its simple iteration. Something along these lines should get you going:

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)
        }
    }
}

Note the various as? type checks to iterate over the structure safely. For a more in-depth review of cleanly working with JSON in Swift including reading the data in to type-safe structs, check out this official blog post from Apple.

Kevin Vaughan
  • 14,320
  • 4
  • 29
  • 22