davidrayowens
davidrayowens

Reputation: 1562

JSON in Swift language

I successfully completely a tutorial on displaying the most recent Top Movies from iTunes in a UITableView using Swift, but now I want to replace the iTunes JSON info with my own. Though it works well and displays the iTunes info, my information does not display. I've tried various things with valueForKeyPathbut still nothing.

.SWIFT FILE

let urlString = "https://itunes.apple.com/us/rss/topmovies/limit=25/json"
var titles = [String]()

func fetchItems(success: () -> ()) {
    let url = NSURL(string: urlString)
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    let task = session.dataTaskWithURL(url) { (data, response, error) in
        var jsonError: NSError?
        let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as NSDictionary

        if let unwrappedError = jsonError{
            println("json error: \(unwrappedError)")
        } else {
            self.titles = json.valueForKeyPath("feed.entry.im:name.label") as [String]
            success()
        }
    }
    task.resume()
}

This works successfully, but when I add the following url instead of iTunes' and try to change the valueForKeyPath I run into runtime errors.

JSON FILE

{"results":[

     {"text":"@twitterapi  http://tinyurl.com/ctrefg",

     "to_user_id":396524,

     "to_user":"TwitterAPI",

     "from_user":"jkoum",

     "metadata":

     {

      "result_type":"popular",

      "recent_retweets": 109



     },

     "id":1478555574,   

     "from_user_id":1833773,

     "iso_language_code":"nl",

     "source":"<a href="http://twitter.com/">twitter< /a>",

     "profile_image_url":"http://s3.amazonaws.com/twitter_production/profile_images/118412707/2522215727_a5f07da155_b_normal.jpg",

     "created_at":"Wed, 08 Apr 2009 19:22:10 +0000"},

     ... truncated ...],

     "since_id":0,

     "max_id":1480307926,

     "refresh_url":"?since_id=1480307926&amp;q=%40twitterapi",

     "results_per_page":15,

     "next_page":"?page=2&amp;max_id=1480307926&amp;q=%40twitterapi",

     "completed_in":0.031704,

     "page":1,

     "query":"%40twitterapi"}

}

Is this JSON file different somehow from that of iTunes? What would I use as valueForKeyPath?

Upvotes: 0

Views: 497

Answers (2)

Chris Wagner
Chris Wagner

Reputation: 20993

The .text.to_user_id.to_user.from_user in your key path is invalid, text, to_user_id to_user and from_user are all siblings.

If you want from_user your keypath should be results.from_user

Upvotes: 3

ktzhang
ktzhang

Reputation: 4157

The JSON file you provided looks fine, but put it through http://jsonlint.com/ to make sure.

Also make sure your valueForKeyPath is correct. I suggest trying to play around with Apple's one to make sure it works first before going on to yours.

Upvotes: 0

Related Questions