I am building an app, in which I want to populate UITableViewCell
from CoreData. In CoreData I am able to save data from server and also able to fetch data. But when my internet is offline I am unable to retrive data from CoreData or there is no data in CoreData. How can I fetch last saved data from CoreData when my internet is offline?
I am saving data using following function:
func SetPremiumValues(Array : NSArray){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("PremiumJob", inManagedObjectContext:managedContext)
for i in Array{
let PremiumJob = NSManagedObject(entity: entity!,insertIntoManagedObjectContext: managedContext)
if let rowData :NSDictionary = i as? NSDictionary{
PremiumJob.setValue(rowData["company"], forKey: "company")
PremiumJob.setValue(rowData["city"], forKey: "city")
PremiumJob.setValue(rowData["id"], forKey: "id")
let ImageName = rowData["user_logo"] as? String
let image = "http://dev.jobsmarket.pk/uploads/user-logo/"+ImageName!
let url = NSURL(string: image)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
if let data = NSData(contentsOfURL: url!) {
PremiumJob.setValue(data, forKey: "user_logo")
}
}
PremiumJob.setValue(rowData["title"], forKey: "title")
PremiumJob.setValue(rowData["fe_short_description"], forKey: "fe_short_description")
}
do {
try managedContext.save()
print("saving premium job is this \(PremiumJob)")
self.Premium.append(PremiumJob)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
}
// fetching data using fetch request
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "PremiumJob")
do{
let results = try managedContext.executeFetchRequest(fetchRequest)
for ManagedObject in results {
let managedObjectData : NSManagedObject = ManagedObject as! NSManagedObject
print("premium data from fetch request \(managedObjectData)")
}
}
catch{
}
}