How to save data to model coredata - ios

I want to save my data to core data when a button is clicked here is my action button code now let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: context)
let cart = Cart(entity: entity!, insertIntoManagedObjectContext: context) but the only problem now is that i dont how to save here is my code to parse json
Alamofire.request(.GET, url!, headers: headers).responseJSON { (response) in
let result = response.result
if response.result.isSuccess{
let jsonObj = JSON(result.value!)
if let x = jsonObj["Items"].array {
x.forEach
{
if let uw = ($0["name"]).string{
print(uw)
let qw = ($0["image"]).string
if let rw = ($0["price"]).int{
if let hu = ($0["id"]).int{
print(hu)
let foo = Rest(name: uw, imageUrl: qw!, price: "₦\(rw)")
self.rest.append(foo)
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
actInd.stopAnimating()
}
}
}
So i have an array called rest which is where i want get data for the tableview. I want to save information of each cell tapped into coredata here is a screenshot of the app
So when the sure button is tapped it saves the item to coredata
here is my code incase you neecode

Try this, adapted to your code.
In the portion that you have (...let app=...) replace it by this:
let app2 = UIApplication.sharedApplication().delegate as! UIApplicationDelegate
if let context2 = app2.managedObjectContext {
let cart2 = NSEntityDescription.insertNewObjectForEntityForName("Cart", inManagedObjectContext: context2) as! Cart
cart2.name = self.res.name
cart2.price = self.res.price
cart2.url = self.res.imageUrl
cart2.id = ""
// Perform a save operation
do {
try context2?.save()
} catch {
let saveError = error as NSError
print(saveError)
}
}
Let me know if this works.
Cheers

Just an example here when you want to save your data in coredata. You have to create entity/model and all the setup for core data elements. For details please study https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial
func saveName(name: String) {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let entity = NSEntityDescription.entityForName("Person",
inManagedObjectContext:managedContext)
let person = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
//3
person.setValue(name, forKey: "name")
//4
do {
try managedContext.save()
//5
people.append(person)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}

Related

How to update objects in core data?

I want to update my core-data entity and my code is:
let ff: Cart!
let indexPath = self.tableView?.indexPathForSelectedRow
ff = self.cart[indexPath!.row]
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: context)
let cartt = Cart(entity: entity!, insertIntoManagedObjectContext: context)
cartt.name = ff.name
cartt.price = Double(ff.price!)
cartt.rest_id = ff.rest_id
cartt.longg = ff.longg
cartt.latt = ff.latt
cartt.item_id = ff.item_id
cartt.restName = ff.restName
cartt.cookTime = ff.cookTime
ff.setValue(Int(txt.text!), forKey: "quantity")
do{
try context.save()
self.viewDidLoad()
print(cartt.longg)
print(cartt.delivery)
print("saved")
}catch{
print("could not save")
}
The element is updating in the core data, but it is also adding a new row to my tableView with an empty data.
If you want to update quantity of the current object ff try with these lines.
let ff: Cart!
let indexPath = self.tableView?.indexPathForSelectedRow
ff = self.cart[indexPath!.row]
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
ff.setValue(Int(txt.text!), forKey: "quantity")
do{
try context.save()
self.viewDidLoad() // why you call this line here ?
print(cartt.longg)
print(cartt.delivery)
print("saved")
}catch{
print("could not save")
}
Why did you call self.viewDidLoad()?
On your next code, you was creating a new item rather than just updating the current one.

Delete core data items

How can i delete all the data in a particular attribute in an entity i don't want to empty all the attributes in the entity here is what i have now which deletes all the attributes in an entity
func deletObject(){
let fetchRequest = NSFetchRequest()
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
fetchRequest.includesPropertyValues = false
let context:NSManagedObjectContext = appDel.managedObjectContext
let moc = context
fetchRequest.entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: moc)
do {
if let results = try moc.executeFetchRequest(fetchRequest) as? [NSManagedObject] {
for result in results {
moc.deleteObject(result)
}
try moc.save()
self.cart = [Cart]()
self.tableView.reloadData()
totalAmouLa.text = "₦\(Int(totalHoursWorkedSum))"
}
} catch {
print("FAILED")
}
}
EDIT
I want to delete delivery in the Cart entity
Image
You cannot delete an attribute from the Core Data model, you can only reset the value.
executeFetchRequest returns guaranteed [Cart] on success, the optional binding will never fail
func deletObject(){
let fetchRequest = NSFetchRequest()
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext
fetchRequest.entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: context)
do {
let results = try context.executeFetchRequest(fetchRequest) as! [Cart]
results.forEach { $0.delivery = 0.0 }
try context.save()
self.tableView.reloadData()
totalAmouLa.text = "₦\(Int(totalHoursWorkedSum))"
} catch {
print("FAILED")
}
}

fetching a custom object from core data into an array

I'm having trouble fetching my object from core data. Object looks like this:
class cilj: NSObject {
var imeCilja: String
var slikaCilja: String }
My entity is called Entity and has two Attributes "tekst" and "slika", both of type String. My save func is this:
func saveImage(goalName:String, imageName:String) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("Entity", inManagedObjectContext:managedContext)
let thingToSaveToCD = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext: managedContext)
thingToSaveToCD.setValue(globalGoalTitle, forKey: "tekst")
thingToSaveToCD.setValue(globalGoalImagePath, forKey: "slika")
do {
try managedContext.save()
print("managed to save to core data")
//5
// listaObjekata.append(cilj5) as! [cilj]
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
I use an alertController to pick up the text, and imagePicker to pick up image that I then store in documents and get the path. I store both of these in a global variables visible in the code above.
My fetch function is :
func coreDataFetch(){
//core data fetch
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let fetchRequest = NSFetchRequest(entityName: "Entity")
do {
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [cilj]
listaObjekata = fetchedResults
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
I have been through ray wenderlich's article on Core Data, Apple's documentation, a couple of YT videos but I still seem to be missing something. I would greatly appreciate any help. Thanks !
EDIT - here is my cellForRowAtIndexPath
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell") as! cellController
let ciljZaPrikaz = listaObjekata[indexPath.item]
cell.labelText.text = ciljZaPrikaz.imeCilja ?? "no text found"
let path = getDocumentsDirectory().stringByAppendingPathComponent(ciljZaPrikaz.slikaCilja)
cell.imageToShow.image = UIImage(contentsOfFile: path)
return cell
}
You are doing correct but just missing type casting to your model. Try below:
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest)
if let results = fetchResults where results.count > 0 {
let entityModel = results[0] as? Entity
let tekst = entityModel.tekst
}
I would also like to add how I iterate through my return objects from core data:
do {
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest)
listaObjekata.removeAll()
for i in 0...(fetchedResults.count-1) {
let enityModel = fetchedResults[i] as? Entity
let thisToArray = cilj(imeCilja: (enityModel?.tekst!)!, slikaCilja: (enityModel?.slika!)!)
listaObjekata.append(thisToArray)
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}

how can i store and show data of core data when internet is not available?

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{
}
}

Save a list of data into core data iOS Swift

I'm doing save a list of data into core data by using the for each loop here. However, it only helping me to save the last data in the for loop into core data, what problem is it? I couldn't manage to save all the data into core data. Below is my code that I'm working on it...
let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context : NSManagedObjectContext = appDelegate.managedObjectContext
let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext:context)
RestApiManager.sharedInstance.makeGetRequest("testingserver", onCompletion: {json in
for result in json["record"].arrayValue
{
print(result)
let id = result["mc_termid"].stringValue
let name = result["mc_name"].stringValue
let parent = result["mc_parent"].stringValue
let color = result["mc_color"].stringValue
let update = result["mc_updated"].stringValue
let termName = result["mc_termname"].stringValue
let status = result["mc_status"].stringValue
category.setValue(id, forKey: "mc_termid")
category.setValue(name, forKey: "mc_name")
category.setValue(parent, forKey: "mc_parent")
category.setValue(color, forKey: "mc_color")
category.setValue(update, forKey: "mc_updated")
category.setValue(termName, forKey: "mc_termname")
category.setValue(status, forKey: "mc_status")
}
do
{
try context.save()
print("Category save to local database successfully.")
}
catch
{
}
})
You need to insert an managedobject every time you iterate one element in the array.
So put the category declaration into the iterating block.
let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context : NSManagedObjectContext = appDelegate.managedObjectContext
RestApiManager.sharedInstance.makeGetRequest("testingserver", onCompletion: {json in
for result in json["record"].arrayValue
{
let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext:context)
print(result)
let id = result["mc_termid"].stringValue
let name = result["mc_name"].stringValue
let parent = result["mc_parent"].stringValue
let color = result["mc_color"].stringValue
let update = result["mc_updated"].stringValue
let termName = result["mc_termname"].stringValue
let status = result["mc_status"].stringValue
category.setValue(id, forKey: "mc_termid")
category.setValue(name, forKey: "mc_name")
category.setValue(parent, forKey: "mc_parent")
category.setValue(color, forKey: "mc_color")
category.setValue(update, forKey: "mc_updated")
category.setValue(termName, forKey: "mc_termname")
category.setValue(status, forKey: "mc_status")
}
do
{
try context.save()
print("Category save to local database successfully.")
}
catch
{
}
})

Resources