aaa
aaa

Reputation: 1649

UITableView Couldn't fetch from Core Data on first launch

So I built an app to read some JSON data from a Web API. Then it parses the JSON and store the result into Core Data. In viewDidLoad of my UITableViewController I tried to read JSON and save the result to Core Data. Then in viewWillAppear I tried to fetch the data from Core Data and save it to users array.

//parse JSON and save result to CoreData
let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)

person.setValuesForKeysWithDictionary([...])

do {
    try managedContext.save()
    users.append(person)
} catch let error as NSError {
    print("Could not save \(error), \(error.userInfo)")
}


override func viewWillAppear(animated: Bool) {
    fetchData()        
}

// fetch from Core Data and save to users array
class func fetchData() {

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: "User")

    do {
        let res = try managedContext.executeFetchRequest(fetchRequest)
        users = res as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
}

// code for refreshing
func refresh() {
    if isConnectedToNetwork() {
        // run some code to read newest data from Web
        self.tableView.reloadData()
    }

    self.refreshControl!.endRefreshing()
}

Now I have this really weird problem that when the app is launched for the first time(on both simulators and my iPhone), the tableview is always empty (but it will be populated with data after refreshing through pulling down). But when I try to build and run it again everything will look OK. Notice that I have tried adding self.tableView.reloadData() to both viewWillAppear and viewDidLoad and both inside a dispatch_async block and outside. Can somebody please tell me what is going on?

Upvotes: 1

Views: 647

Answers (1)

Imran
Imran

Reputation: 2941

When you run your app for the first time in your viewDidLoad you laid data from url and parse and then insert in core data meanwhile in your viewWillAppear will already called as your data is not still inserted in core data so you will see empty tableview. You can call fetchData() and self.tableView.reloadData() after you insert the data, for the first time run fix.

Upvotes: 1

Related Questions