vardantandon
vardantandon

Reputation: 51

JSON Parsing in Swift

I was doing the JSON Parsing in Swift tutorial by Ray Wenderlich.

While using DataManager.getTopAppsDataFromAppsWithSuccess in viewDidLoad(), Its unable to print out the array when its outside the DataManager block.

Does someone know how to get the array values outside that block ?

Code :

var apps = [String]()
override func viewDidLoad() {
  DataManager.getTopAppsDataFromAppsWithSuccess { (ByodData) -> Void in
    let json = JSON(data: ByodData)
       if let appArray = json.array{
        for appDict in appArray {
          var appName: String = appDict["name"].stringValue
          self.apps.append(appName)
         }
      }
  println(self.apps)
}

Input JSON:

[
   {
       "id":1,
       "name":"AdobeReader",
       "url":"comp2014group1.herokuapp.com/apps/1.json";
   },
   {
       "id":2,
       "name":"BBCiPlayer",
       "url":"comp2014group1.herokuapp.com/apps/2.json";
   },
   {
       "id":3,
       "name":"BBCNews",
       "url":"comp2014group1.herokuapp.com/apps/3.json";
   },
   {
       "id":4,
       "name":"BBCWeather",
       "url":"comp2014group1.herokuapp.com/apps/4.json";
   }
]

Output :

[]

Upvotes: 2

Views: 517

Answers (1)

ljk321
ljk321

Reputation: 16790

This function getTopAppsDataFromAppsWithSuccess seems to be an async one, which will not block execution. Thus the println(self.apps) is immediately executed before the data is actually retrieved.

The JSON data should be OK. Just don't try to print it like that. You can use the JSON data after it's ready.

Upvotes: 1

Related Questions