UI TableView cell opening a new view with multiple data using coredata in swift - iphone

as a beginner in iOS and Swift, I have a project that has to have a tableview with multiple cells, in which every cell contains several data types. i.e. Strings, dates etc., where in one view controller, there is the table view for viewing the cells, the second view controller is for creating a cell and entering the data, and the third view is for displaying the same data when clicking the cell. I've decided to store all of that using coredata since I was told it's most efficient and simple for beginners. I've used several tutorials on this matter but none of them handle this type of problem I have. Best example is how the Contact list works on iOS.
The code I've done so far is this:
var titleCellList = [NSManagedObject]()
var infoCellList = [NSManagedObject]()
class CellsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var cellsTableView: UITableView!
//MARK: Default Functions
override func viewDidLoad() {
super.viewDidLoad()
title = "\"Lists\""
cellsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
// Do any additional setup after loading the view.
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TitleCellList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
let cellTitle = titleCellList[indexPath.row]
cell.textLabel!.text = cellTitle.valueForKey("title") as? String
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
cellsTableView.reloadData()
}
//MARK: Storing CoreData
func saveName(name: String) {
//1
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
//2
let entity = NSEntityDescription.entityForName("Data", inManagedObjectContext: managedContext)
let title = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)
//3
title.setValue(name, forKey: "title")
//4
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
//5
titleCellList.append(title)
}
//MARK: Fetching CoreData
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//1
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
//2
let fetchRequest = NSFetchRequest(entityName:"Data")
//3
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]
if let results = fetchedResults {
titleCellList = results
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
}
// MARK: Table Editing Methods
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
context.deleteObject(titleCellList[indexPath.row] as NSManagedObject)
titleCellList.removeAtIndex(indexPath.row)
context.save(nil)
cellsTableView.reloadData()
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
println("Row: \(row)")
println(titleCellList[row])
performSegueWithIdentifier("checkCellSegue", sender: self)
}
Second View Controller (the one for creating a cell with data)
class AddNewViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var titleTextField: UITextField!
#IBOutlet var shortInfoTextView: UITextView!
//MARK: Default Functions
override func viewDidLoad() {
super.viewDidLoad()
self.titleTextField.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
#IBAction func addDataButtonPressed(sender: UIButton) {
if titleTextField.text != "" {
CellsViewController().saveName(titleTextField.text)
titleTextField.text = ""
shortInfoTextView.text = ""
println("New title Added!")
}else {
println("No empty titles allowed!")
}
}
Now, most of this code is from a tutorial, and when I tried adding other data entity's, it didn't work. In the datamodel I currently have only 1 entity named "Data" which contains 4 models. So, to sum it up, I need to store 4 data models in one entity and load them on a different view controller when clicking on a cell which of course, has a title that the user wrote. And just to note, I've spent hours searching online for an answer so this is my last line so to say.
Any help would be greatly appreciated.

So, here is the one approach I used on this little issue. I basically just pass arguments with the prepareForSegue method, and inside of it I just pass the data I want to use in the other class/VC.
The Code:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Setter for Second VC, destination path --> var declarations in Second VC
if segue.identifier == "checkCellSegue" {
let destination = segue.destinationViewController as! SecondViewController
if let indexPath = self.tableView?.indexPathForCell(sender as! UITableViewCell) {
let object = fetchedResultsController?.objectAtIndexPath(indexPath) as? Data
destination.cellTitle = object?.cellTitle
destination.textViewInfo = object?.textViewInfo
destination.timerValue = object?.timerValue
}
}
So, first we declare the destination which is the name of our Second VC or whatever you named it. Then, since I am accessing data trough a TableView cell we need to fetch my CoreData Entity with the indexPath. After that the final declaration is the Model Class which has all the data values from the entity, which will work like a singleton.
destination.cellTitle // --> in the 2.nd VC we declared a new var called cellTitle, var cellTitle:String
object?.cellTitle // --> in the model class "Data.swift" the declaration is #NSManaged var cellTitle:String
So, thats it. I am still a little newbie on iOS so if there are any mistakes, just say so.

Related

Swift: How to fetch Relationship Core Data by Month

I'm new to Swift and need your help.
I have two View Controllers with a tableview and two Entities called Groups and Singlegroups with an one to many relationship.The Entity Singlegroups has an attribute from type Date.
In View Controller 1 (MasterViewController) I show all Groups in my TableView and in the second View Controller (DetailViewController) I show all Singlegroups related to the Group of the selected row.
Now I want to load the SingleGroups on second View Controller only from current month but I can't get it to work, because I have no FetchRequest in the second View Controller. I transfer the Single Groups for the selected row in the prepareForSegue method.
I tried to call a fetchRequest manually in thousands different ways but nothing happend.
Hope you understand my problem and can help me.
MasterViewController ViewWillAppear:
import UIKit
import CoreData
class MasterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var groups: [Groups] = []
#IBOutlet weak var groupsTableView: UITableView!
var groupsTextField: UITextField?
override func viewDidLoad() {
super.viewDidLoad()
groupsTableView.delegate = self
groupsTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
// Core date initialization
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest: NSFetchRequest<Groups> = Groups.fetchRequest()
do {
groups = try managedContext.fetch(fetchRequest)
groupsTableView.reloadData()
} catch {
// TODO: error handling
print("Could not fetch groups")
}
}
PrepareForSegue in MasterViewController:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetailViewController" {
guard let destination = segue.destination as? DetailViewController,
let selectedRow = self.groupsTableView.indexPathForSelectedRow?.row else {
return
}
destination.group = groups[selectedRow]
destination.title = groups[selectedRow].groupTitle
}
DetailViewController ViewWillAppear:
import UIKit
import CoreData
class DetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {
var singleGroupDate: UILabel!
var singleGroupName: UILabel!
var singleGroupAmount: UILabel!
#IBOutlet weak var dateLabelTextField: UITextField!
#IBOutlet weak var singleGroupSum: UILabel!
#IBOutlet weak var singleGroupTableView: UITableView!
var groups: [Groups] = []
var group: Groups?
override func viewDidLoad() {
super.viewDidLoad()
singleGroupTableView.delegate = self
singleGroupTableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
// Core date initialization
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
// create alert
let alert = UIAlertController(
title: "Could not get app delegate",
message: "Could not get app delegate, unexpected error occured. Try again later.",
preferredStyle: .alert)
// add OK action
alert.addAction(UIAlertAction(title: "OK", style: .default))
// show alert
self.present(alert, animated: true)
return
}
let managedContext = appDelegate.persistentContainer.viewContext
singleGroupTableView.reloadData()
DetailViewController TableView:
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return group?.singleGroups?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = singleGroupTableView.dequeueReusableCell(withIdentifier: "SingleGroupsTableViewCell", for: indexPath) as! SingleGroupsTableViewCell
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale.current
currencyFormatter.positivePrefix = currencyFormatter.plusSign
currencyFormatter.negativePrefix = currencyFormatter.minusSign
if let singleGroup = group?.singleGroups?[indexPath.row] {
cell.singleGroupNameLabel?.text = singleGroup.singleGroupName
cell.singleGroupAmountLabel?.text = currencyFormatter.string(from: singleGroup.singleGroupAmount as NSNumber)
cell.singleGroupAmountLabel.textColor = UIColor.red
cell.singleGroupDateLabel?.text = DateHelper.convertDate(date: singleGroup.singleGroupTimeStamp)
}
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
deleteSingleGroup(at: indexPath)
}
}
UPDATE:
I solved it myself by writing a new fetch request for the SingleGroups Entity and changing the numbersOfRowsInSection method of my tableview.
func orderFetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
let startDateFetch = Date().startOfMonth()
let endDateFetch = Date().endOfMonth()
self.startDate = startDateFetch!
self.endDate = endDateFetch!
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "SingleGroups")
let sortDescriptor = NSSortDescriptor(key: "singleGroupTimeStamp", ascending: false)
let predicate1 = NSPredicate(format: "group == %#", group!)
let predicate2 = NSPredicate(format: "singleGroupTimeStamp >= %# AND singleGroupTimeStamp <= %#", startDate as CVarArg, endDate as CVarArg)
let compound = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1, predicate2])
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.predicate = compound
return fetchRequest
}
func fetchData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = orderFetchRequest()
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedContext, sectionNameKeyPath:nil, cacheName: nil)
do {
try fetchedResultsController.performFetch()
singleGroupTableView.reloadData()
}
catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController.fetchedObjects?.count ?? 0

Swift UITableView cellForRowAt indexPath doesn't get called on tableView.reloadData() after view appeared for second time

The summary of my problem is; when the tableView.reloadData() is called upon firestore's local changes on the first time the view loads up it works and updates as it supposed to. However, after I switch forth and back with other viewControllers, although initially on viewDidAppear() tableView get's reloaded, upon local changes it no longer does so.
I've included a simpler version of my project to better explain and to make it reproducable;
Class Item
let db = Firestore.firestore()
static var list = [String:[String:Any]]()
static var listenerSet = Bool()
static var listener: ListenerRegistration!
func setListener(completion: #escaping (String) -> Void) {
if !Item.listenerSet {
print("Attaching item document listener.")
Item.listener = db.collection("Items").document("default").addSnapshotListener({ (document, error) in
let source = document!.metadata.hasPendingWrites ? "Local" : "Server"
print("Updating item data from the \(source).")
Item.listenerSet = true
Item.list = document?.get("List") as! [String:[String:Any]]
completion("Item data is set")
})
} else {
completion("Item listener already exists")
}
}
func add(itemID:String) {
let itemRef = db.collection("Items").document("default")
itemRef.setData([
"List": [
itemID : [
"Count": FieldValue.increment(1.0),
]]
], merge:true)
}
FirstViewController:UIViewController
let item = Item()
var itemList = [[String:Any]]()
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var switchBar: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Setting the table views
tableView.delegate = self
tableView.dataSource = self
}
override func viewDidAppear(_ animated: Bool) {
print("View Did appear") // prints OK
item.setListener() { (result) in
print(result)
loadData()
}
}
func loadData() {
itemList.removeAll()
var counter = 0
for (id,data) in Item.list {
itemList.append(data)
itemList[counter]["ID"] = id
counter += 1
}
tableView.reloadData()
}
#IBAction func switchBarChanged(_ sender: UISegmentedControl) {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
switch switchBar.selectedSegmentIndex {
case 1:
let vc = storyBoard.instantiateViewController(identifier: "secondViewController")
show(vc, sender: self)
default:
break
}
}
Extension FirstViewController: UITableViewDataSource,UITableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("These are items:\(itemList)")
print(itemList.count)
print(tableView.bounds.height)
return itemList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell") as! ItemCell
let itemID = itemList[indexPath.row]["ID"] as! String
let itemName = itemList[indexPath.row]["Name"] as! String
let itemCount = itemList[indexPath.row]["Count"] as! Double
cell.itemID = itemID
cell.itemName.text = itemName
cell.itemCount.text = String(itemCount)
print("Items within the tableView \(itemList)") // prints only in the first run whenever there is an upload, or when refreshed.
return cell
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let add = UIContextualAction(style: .normal, title: "Add", handler: { (action, view, completionHandler) in
item.add(itemID:(itemList[indexPath.row]["ID"] as! String))
completionHandler(true)
})
add.image = UIImage(systemName: "plus")
let configuration = UISwipeActionsConfiguration(actions: [add])
configuration.performsFirstActionWithFullSwipe = true
return configuration
}
Class ItemCell:UITableViewCell
var itemID = String()
#IBOutlet weak var itemName: UILabel!
#IBOutlet weak var itemCount: UILabel!
SecondViewController:UIViewController
#IBOutlet weak var switchBar: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func switchBarChanged(_ sender: UISegmentedControl) {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
switch switchBar.selectedSegmentIndex {
case 0:
let vc = storyBoard.instantiateViewController(identifier: "firstViewController")
show(vc, sender: self)
default:
break
}
}
Now this is the flow I'm having issue on;
Application loads, FirstViewController loads, viewDidAppear kicks in. tableView loads.
When swiped right, the value in firestore server increments by one, snapshot listener kicks in, tableview reloads and everything works as it supposed to be.
After I switch to SecondViewController and come back to FirstViewController, viewDidAppear kicks in tableView loads.
This time however, when I swipe right again, the value in firestore server still increments by one and the snapshot listener kicks in, updating the Item.list. static var ItemList gets updated, and tableView does reload, however this time, only numberOfRowsInSection method works as it prints the count and updated itemList, then nothing happens cellForRowAt doesn't work and rows don't get updated.
Now at this stage if I go SecondViewController and comeback to FirstViewController the rows are updated, but when swiped right still no avail.
What am I missing here ? Thanks all for your replies.

Table view not updating with Firebase

I am trying to get a table view to update from my Firebase database. My data is structured like this (for reporting automobiles):
Reports:
Randomly generated report ID number:
make: "make of car"
model: "make of model"
I don't think that I am calling the data correctly. I do not know how to select for the random report ID. But there may be something else that I am missing. I am trying to get only the make and model of the vehicle to display in the text of the cell
var reportList:[String] = []
var ref: DatabaseReference!
var handle: DatabaseHandle?
#IBOutlet weak var reportsTableView: UITableView!
#IBAction func backButtonPressed(_ sender: UIBarButtonItem) {
self.performSegue(withIdentifier: "reportsToHome", sender: self)
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return reportList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = reportList[indexPath.row]
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
handle = ref.child("Reports").observe(.childAdded, with: { (snapshot) in
if (snapshot.value as? String) != nil
{
let make = String(describing: self.ref.child("Reports").child("make"))
let model = String(describing: self.ref.child("Reports").child("model"))
self.reportList.append(make + model)
self.reportsTableView.reloadData()
}
}
// Do any additional setup after loading the view.
)}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I'm not able to test this, but I have feeling that you were trying to cast the snapshot as a string. Instead, you should cast it as a Dictionary so you can easily retrieve the data by key.
Try this code. It sets the snapshot as a dictionary, and from there you are able to retrieve the make and model:
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
handle = ref.child("Reports").observe(.childAdded, with: { (snapshot) in
if let reports = snapshot.value as? NSDictionary {
var make = reports?["make"] as? String
var model = reports?["model"] as? String
self.reportList.append(make + model)
self.reportsTableView.reloadData()
}
}
)}
Going further, you can create a Report class:
class Report: NSObject {
var make: String?
var model: String?
}
You can then set the make and model from the snapshot to create a new Report object.
var make = reports?["make"] as? String
var model = reports?["model"] as? String
let newReport = Report()
newReport.setValuesForKeys(reports)
I hope this works, if not I'll look again.

UITableView not displaying the correct number of sections and rows from the fetch request array result

I think my problem spans over multiple VC.
In the table VC I perform a fetch request that returns an array of Floor objects. This entity has 2 attributes (floor number and number of rooms in floors). If I assign 2 floors (0 and 1) it works and prints them. The next VC contains a picker that displays the number of floors and a text box that is used to assign the number of rooms per floor. There must be a problem with this function because it gets called only if the first item of the picker is selected (prints the result). If I have 2 floors (0 and 1 in the picker) and floor 1 is selected the function does not assign the room value to any other floor. It doesn't matter how many floors, the function will only work for the first one. I have looked of how to modify the function but did not find any suitable solutions.
The second problem is that the table view does only display one row. Lets say that for floor 0 I assign 1; than only a row with 1 appears. If anyone could help me it would mean a lot to me. Thank you
Please see the code below for the picker function:
#IBAction func setTheFloors(_ sender: UIButton) {
if storedFloors.count > 0 {
if storedFloors.first?.floorNumber == pickedFloor! {
storedFloors.first?.numberOfRooms = roomNumberValue
print("\(storedFloors.first?.floorNumber) + \(storedFloors.first?.numberOfRooms)")
}
}
do {
try managedObjectContext.save()
} catch {
fatalError("could not save context because: \(error)")
}
}
#IBAction func nextStep(_ sender: UIButton) {
}
private func loadFloorData() {
let floorRequest: NSFetchRequest<Floors> = Floors.fetchRequest()
do {
storedFloors = try managedObjectContext.fetch(floorRequest)
} catch {
print("could not load data from core \(error.localizedDescription)")
}
}
private func spinnerItems() {
for i in 0...floorValue! - 1 {
convertedFloorValues.append(String(i))
}
}
and this section of code is for the table view.
class RoomAndAlarmTypeTableVC: UITableViewController, NSFetchedResultsControllerDelegate {
//MARK: - Properties
private var managedObjectContext: NSManagedObjectContext!
private var storedFloors = [Floors]()
private var floorsAndRooms = [String: String]()
//MARK: - Actions
override func viewDidLoad() {
super.viewDidLoad()
managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
loadFloorData()
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func loadFloorData() {
let floorRequest: NSFetchRequest<Floors> = Floors.fetchRequest()
do {
storedFloors = try managedObjectContext.fetch(floorRequest)
print("\(storedFloors)")
} catch {
print("could not load data from core \(error.localizedDescription)")
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return storedFloors.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let specificFloor = storedFloors[section]
return Int(specificFloor.numberOfRooms)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "house cell", for: indexPath) as! ViewRooomNumberCell
let tableSections = storedFloors[indexPath.section]
let floorItem = tableSections.numberOfRooms[indexPath.row]
let floorNumber = String(floorItem.numberOfRooms)
cell.floorNumberTxt.text = floorNumber
return cell
}
}

Can't update a value with Core Data

first i come from France so sorry for my english.
Second, I'm new in developpement and i have develop a code for add data and after show them with Core Data. it works.ok
but after i want update but i have a problem i don't know why i can't update my value. There is an error : "fatal error: unexpectedly found nil while unwrapping an Optional value"
i have try many solution since 1 week, but can't find the problem. Thanks if someone can help me ! even a little help :)
this is my code (swift 2.3) :
for show in table view :
import UIKit
import CoreData
class ProduitTableViewController: UITableViewController {
#IBOutlet var table: UITableView!
var produits = [NSManagedObject]()
func refreshStories(refreshControl: UIRefreshControl) {
produits.removeAll()
fetchData()
self.table.reloadData()
refreshControl.endRefreshing()
}
override func viewDidLoad() {
super.viewDidLoad()
self.fetchData()
self.table.addSubview(self.refreshControl!)
self.refreshControl?.addTarget(self, action: #selector(ProduitTableViewController.refreshStories(_:)), forControlEvents: UIControlEvents.ValueChanged)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fetchData() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let fetchRequest = NSFetchRequest(entityName: "Produits")
let sort = NSSortDescriptor(key:"dateAjout", ascending:true)
fetchRequest.sortDescriptors = [sort]
//3
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
produits = results as! [NSManagedObject]
} catch let error as NSError {
print("Donnees non recu \(error), \(error.userInfo)")
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.produits.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
let produit = produits[indexPath.row]
cell!.textLabel!.text = produit.valueForKey("nom") as? String
/*
let id = produit.valueForKey("id") as? String
let date = produit.valueForKey("date") as? NSDate
let localNotification = UILocalNotification()
localNotification.userInfo = ["id" : id!]
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.alertBody = "expiré"
localNotification.fireDate = date
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
UIApplication.sharedApplication().applicationIconBadgeNumber += 1
*/
return cell!
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let supprimer = UITableViewRowAction(style: .Normal, title: "Suppr.") { action, index in
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let moc = appDelegate.managedObjectContext
// 3
moc.deleteObject(self.produits[indexPath.row])
appDelegate.saveContext()
// 4
self.produits.removeAtIndex(indexPath.row)
tableView.reloadData()
}
supprimer.backgroundColor = UIColor.redColor()
let update = UITableViewRowAction(style: .Normal, title: "Modifier") { action, index in
}
update.backgroundColor = UIColor.blueColor()
return [supprimer]
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// the cells you would like the actions to appear needs to be editable
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "showDetail" {
if let destination = segue.destinationViewController as? DetailViewController {
let row = table.indexPathForSelectedRow?.row
let produit = produits[row!]
let nom = produit.valueForKey("nom") as? String
let id = produit.valueForKey("id") as? String
let detail = produit.valueForKey("detail") as? String
let date = produit.valueForKey("date") as? NSDate
let time = date
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-YY HH:mm"
let formatteddate = formatter.stringFromDate(time!)
destination.dataNom = nom!
destination.dataId = id!
destination.dataDetail = detail!
destination.dataDate = formatteddate
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if table.cellForRowAtIndexPath(indexPath) != nil {
self.performSegueWithIdentifier("showDetail", sender: self)
}
}
}
for show detail of the cell :
import CoreData
import UIKit
class DetailViewController: UIViewController {
#IBOutlet var Label: UILabel!
#IBOutlet var Detail: UITextView!
#IBOutlet weak var Date: UILabel!
#IBOutlet weak var Id: UILabel!
var dataNom = ""
var dataDetail = ""
var dataDate = ""
var dataId = ""
override func viewDidLoad() {
super.viewDidLoad()
Label.text = dataNom
Detail.text = dataDetail
Date.text = dataDate
Id.text = dataId
// Do any additional setup after loading the view
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "ModifierDetail" {
if let destination = segue.destinationViewController as? ModifierViewController {
destination.modifierNom = dataNom
destination.modifierId = dataId
destination.modifierDetail = dataDetail
destination.modifierDate = dataDate
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
And the last for update/modify my detail:
import UIKit
import CoreData
class ModifierViewController: UIViewController {
#IBOutlet weak var Nom: UITextField!
#IBOutlet weak var Detail: UITextView!
#IBOutlet weak var Date: UITextField!
var Produits: NSManagedObject!
var managedContext: NSManagedObjectContext!
var modifierNom = ""
var modifierDetail = ""
var modifierDate = ""
var modifierId = ""
override func viewDidLoad() {
super.viewDidLoad()
Nom.text = modifierNom
Detail.text = modifierDetail
Date.text = modifierDate
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Annuler(sender: UIBarButtonItem) {
navigationController?.popViewControllerAnimated(true)
}
#IBAction func Modifier(sender: UIButton) {
let fetchRequest = NSFetchRequest(entityName:"Produits")
fetchRequest.predicate = NSPredicate(format: "nom = %#", modifierNom)
do {
let list = try managedContext.executeFetchRequest(fetchRequest) as! [Produit]
if list.count == 0 // Check notificationId available then not save
{
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Produits", inManagedObjectContext: managedContext)
newManagedObject.setValue(modifierNom, forKey: "nom")
}
// success ...
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
i have create this other file:
import Foundation
import CoreData
#objc(Produit)
class Produit: NSManagedObject {
#NSManaged var nom:String!
}
As you mentioned in the comment, this line causes the crash:
let list = try managedContext.executeFetchRequest(fetchRequest) as! [Produit]
That line is not safe, because you don't know, if casting to [Prodiut]will always be successful.
In general, you should never force-cast (as!) or force-unwrap (!) something when you don't know 1000%, that it will succeed.
To cast safely, you can use guard:
guard let list = try managedContext.executeFetchRequest(fetchRequest) as! [Produit] else {
//do some error handling here and then return
return
}
After that, you can safely use list.
It's really important to understand, what optionals are and how to handle them safely without crashes.