0

I've just started with Swift and I'm trying to loop through a json response and add it to a dictionary. But nothing seems to be added, not sure what the problem is maybe scope? I'm using SwiftyJSON. In my code i'm able to print the news title within the for loop like so json[0]["title"] etc. But when I print the values of the dictionary nothing is ouputted.

// news dictionary
var newsDictionary = [String] ()

override func viewDidLoad() {
    super.viewDidLoad()

    // get news feed url
    let url = NSURL(string: baseUrl + "news")

    // create session
    let session = NSURLSession.sharedSession()

    // create data task
    let task = session.dataTaskWithURL(url!, completionHandler: { (data: NSData!, response:NSURLResponse!,
        error: NSError!) -> Void in

        // convert data object to json
        let json = JSON(data: data)

        for var i = 0; i < json.count; ++i {
            // get news title from json object
            var title = json[i]["title"].string
            // add to dictionary
            self.newsDictionary.append(title!)
        }

    })

    for news in newsDictionary{
        println(news)
    }

    // execute call
    task.resume()





    // Do any additional setup after loading the view.
}
Jonnny
  • 4,939
  • 11
  • 63
  • 93
  • 1
    You'll have to understand that `dataTaskWithURL()` works *asychronously*. See for example http://stackoverflow.com/questions/27208198/function-does-not-wait-until-the-data-is-downloaded. – Martin R Mar 18 '15 at 18:48

1 Answers1

2

This is because you have a race condition. Very likely your for news in newsDictionary loop is executing before any data is downloaded and processed in session.dataTaskWithURL.

Put your for loop inside the completionHandler and you should see data.

tng
  • 4,286
  • 5
  • 21
  • 30
  • What would that look like code wise? Apologies for my novice status! – Jonnny Mar 18 '15 at 18:54
  • 1
    You already have a completion handler written, just move the "for news in newsDictionary" loop so that it is immediately following the other for loop. Basically, it would just need to be before the }) – Will M. Mar 18 '15 at 19:01