Parsing the Twitter Response

Inside our handleTwitterData method, we receive the raw data from the Twitter API and can use it to update our UI.

We’ll start by handing the raw data over to Foundation’s NSJSONSerialization, which can easily produce either an NSArray or NSDictionary of the parsed data, an object that may itself be a deep structure of nested arrays and/or dictionaries. Let’s do a quick sanity check by following the NSLog statement with this:

1: private​ ​func​ handleTwitterData (data: ​NSData​!,
urlResponse: ​NSHTTPURLResponse​!,
error: ​NSError​!) {
guard​ ​let​ data = data ​else​ {
5: NSLog​ (​"handleTwitterData() received no data"​)
return
}
NSLog​ (​"handleTwitterData(), ​​(​data.length​)​​ bytes"​)
do​ {
10: let​ jsonObject = ​try​ ​NSJSONSerialization​.​JSONObjectWithData​(data,
options: ​NSJSONReadingOptions​([]))
NSLog​ (​"JSON is:​​ (​jsonObject​)​​"​)
} ​catch​ ​let​ error ​as​ ​NSError​ {
NSLog​ (​"JSON error: ​​(​error​)​​"​)
15:  }
}
  • Lines 1--3 are our method declaration. As explained a while back in Maybe It’s There, Maybe It Isn’t: Optionals, the bang characters (!), indicate the parameters are implicitly unwrapped optionals: they’re still optionals, but we can access their values directly without converting to a non-optional type if we’re sure they can’t be nil. When Apple’s frameworks call back to us like this, they usually send implicitly unwrapped optionals.

  • This is followed by the guard let that we wrote earlier, which bails out if data is nil. Otherwise, we have a non-optional NSData that we can parse in the lines below.

  • The JSONObjectWithData’s third parameter is listed as an NSErrorPointer. That’s the old Objective-C way of handling errors, and we learned back in Handling Errors the Swift 2.0 Way that Swift 2.0 automatically converts this to a try-catch idiom. That means that we need to wrap this call (and any related statements that may throw errors) with a do (line 9). For simplicity, we’ll just catch the error and log it (lines 13--15).

  • We call the NSJSONSerialization method JSONObjectWithData on line 10 to perform the JSON parsing of our data object. Since this is the method that can throw an error, we have to precede it with the try keyword.

    On line 11 we pass in our options for JSONObjectWithData. The NSJSONReadingOptions type is a OptionSetType, which means it’s a Swift wrapper around a C bit-field, a scheme where values are powers of 2, so they can be inspected with bitwise mathematical operators. That’s great for C, but awkward in Swift, so in Swift 2.0, we get to treat them like Sets when we create them and inspect them, so to create an empty NSJSONReadingOptions, we pass in the empty set, [].

  • For the time being, we’re done: we’ve got an array or dictionary of parsed tweet data in parsedJSON. On line 12, we’ll use NSLog to print what we got to the Xcode console.

Run this, wait for the table view to come up, and check the console at the bottom of the Xcode window. The result will be a deeply nested structure, set off by tabs and curly-brace blocks, showing each tweet as a set of name-value pairs. The top of it will look something like this:

 handleTwitterData(), 381073 bytes
 JSON is:
 (
  {
  contributors = "<null>;";
  coordinates = "<null>";
  "created_at" = "Sat Sep 05 20:06:41 +0000 2015";
  entities = {
  hashtags = (
  );

In the response, the first curly brace sets off all the data for one tweet, which has keys named contributors, "created_at", and so on. Notice that the value for entities is a curly brace, with its own child set of keys and values.

We can pick out interesting data like text, which is a string containing the tweet’s text, and user, which is a dictionary of name-value pairs with items like screen_name and followers_count. Everything we could want to know about each tweet is in these entries, meaning we now have the data we need to populate the UI.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.184.117