0

As a beginner iOS developer, I feel like this must be a common problem, but I can't figure it out. Please also tell me if there's a duplicate question.

I have a DataManager which fetches data from an API:

import Foundation
import CoreData
import Alamofire
import SwiftyJSON

class DataManager {

static let dataManager = DataManager()

var resourceArray = [NSManagedObject]()

// etc

func getResourceFromJSON() -> NSArray {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedObjectContext = appDelegate.managedObjectContext

    Alamofire.request(.GET, RESOURCE_REF) .responseJSON { response in
        var fakeArray = [NSManagedObject]()
        if ((response.result.value) != nil) {
            let swiftyJsonVar = JSON(response.result.value!)

            let jsonArray = swiftyJsonVar.arrayObject as! [[String: AnyObject]]
            for item in jsonArray {

                //resource
                let entity = NSEntityDescription.entityForName("Resource", inManagedObjectContext: managedObjectContext)
                let resource = Resource(entity: entity!, insertIntoManagedObjectContext: managedObjectContext)

//              let tag = item["tags"]

                resource.setValue(item["id"], forKey: "id")
                resource.setValue(item["title"], forKey: "title")
                resource.setValue(item["type"], forKey: "type")
                resource.setValue(item["url"], forKey: "url")


                do {
                    try managedObjectContext.save()
                    fakeArray.append(resource)
                } catch let error as NSError {
                    print("Could not save \(error), \(error.userInfo)")
                }
            }
        }
        self.resourceArray = fakeArray
    }
    return resourceArray
}

And in my ViewController class, I am getting the data:

override func viewDidLoad() {
    super.viewDidLoad()
    self.resourceArray = DataManager.dataManager.getResourceFromJSON() as! [NSManagedObject]
}

My problem is: When I run my application, the data only loads on a second load. So basically, when I go to my ViewController class the first time, the data doesn't load and the resourceArray has 0 items. But if I load it again, the data will load and my resourceArray is populated.

How can I make it so that my data loads on the first time I go to that view?

Thank you

sallyp
  • 226
  • 3
  • 12
  • 2
    You can't have a return value on your `getResourceFromJSON` function because the data is loaded asynchronously. – rmaddy May 03 '16 at 23:43
  • Oh no, I am really ignorant at asynchronous/synchronous concepts. Is there anything you suggest I can do ? – sallyp May 03 '16 at 23:48

0 Answers0