Issue deleting a row using NSFetchedResultController in swift 2.1 - ios

Hi guys I am using NSFetchedResultController but I am getting issues when I delete a record (even with the first record).
Here is the code of my View Controller :
import UIKit
import CoreData
class FoldersListViewController: UITableViewController, NSFetchedResultsControllerDelegate {
#IBOutlet var myFoldersTableView: UITableView!
// public property that represent the current selected row in a tableview; this will be use in the shouldPerformSegueWithIdentifier
// function because the method doesn't have a parameter for the index path of the selected row.
var selectedRowIndex: NSIndexPath? = nil
//Public property that will be controlling all the manipulation of CoreData.
var fetchedResultController: NSFetchedResultsController!
override func viewDidLoad() {
super.viewDidLoad()
let config = Settings()
config.ReadConfiguration()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.loadFolders()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return fetchedResultController.sections!.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
let sectionInfo = fetchedResultController.sections![section]
return sectionInfo.numberOfObjects
}
func configureCell(cell: cellFolder,indexPath: NSIndexPath)
{
let folder = fetchedResultController.objectAtIndexPath(indexPath) as! Folder
if(folder.picture.length > 0){
let newSize:CGSize = CGSize(width: 64,height: 64)
let rect = CGRectMake(0,0, newSize.width, newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, true, 0.0)
let photo = UIImage(data: folder.picture)
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
photo!.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
cell.imageView?.layer.masksToBounds = true
cell.imageView?.layer.cornerRadius = 15.0
cell.imageView?.clipsToBounds = true
cell.imageView?.image = newImage
}
cell.labelFolderName.text = folder.name
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: cellFolder = tableView.dequeueReusableCellWithIdentifier("cellFolder", forIndexPath: indexPath) as! cellFolder
self.configureCell(cell, indexPath: indexPath)
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
if (tableView.editing){
return false
}
else
{
return true
}
}
func loadFolders() {
let request = NSFetchRequest(entityName: "Folder")
let handler = HACoreDataHandler()
let sortDescriptor = NSSortDescriptor(key: "name",ascending: true)
request.sortDescriptors = [sortDescriptor]
fetchedResultController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: handler.context!, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultController.delegate = self
do
{
try fetchedResultController.performFetch()
} catch let error as NSError {
let alert = UIAlertController(title: "Error", message: error.description, preferredStyle: UIAlertControllerStyle.Alert)
let dismiss = UIAlertAction(title: "Dismiss", style: .Default) { (alertAction: UIAlertAction) ->
Void in
}
alert.addAction(dismiss)
presentViewController(alert, animated: true, completion: nil)
}
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType)
{
let indexSet = NSIndexSet(index:sectionIndex)
switch type {
case .Insert:
myFoldersTableView.insertSections(indexSet, withRowAnimation: .Automatic)
case .Delete:
myFoldersTableView.deleteSections(indexSet, withRowAnimation: .Automatic)
default:
break
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?)
{
switch type{
case .Insert:
myFoldersTableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
case .Delete:
myFoldersTableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
case .Update:
myFoldersTableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
case .Move:
if (indexPath != newIndexPath){
myFoldersTableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
myFoldersTableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
}
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
myFoldersTableView.endUpdates()
}
override func viewWillAppear(animated: Bool) {
self.loadFolders()
myFoldersTableView.reloadData()
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
let item = self.fetchedResultController.objectAtIndexPath(indexPath) as! Folder
let handler = HACoreDataHandler()
handler.context?.deleteObject(item)
var error: NSError?
do {
try handler.context?.save()
} catch let error1 as NSError {
error = error1
}
if(error != nil){
let alert = UIAlertController(title: "Error", message: error?.description, preferredStyle: UIAlertControllerStyle.Alert)
let dismiss = UIAlertAction(title: "Dismiss", style: .Default) { (alertAction: UIAlertAction) ->
Void in
}
alert.addAction(dismiss)
presentViewController(alert, animated: true, completion: nil)
}
self.myFoldersTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .Default, title: "Delete") { (action:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
self.selectedRowIndex = indexPath
let folder = self.fetchedResultController.objectAtIndexPath(indexPath) as! Folder
let handler = HACoreDataHandler()
handler.context?.deleteObject(folder)
do {
try handler.context?.save()
} catch let error as NSError {
let alert = UIAlertController(title: "Error", message: error.description, preferredStyle: UIAlertControllerStyle.Alert)
let dismiss = UIAlertAction(title: "Dismiss", style: .Default) { (alertAction: UIAlertAction) ->
Void in
}
alert.addAction(dismiss)
self.presentViewController(alert, animated: true, completion: nil)
}
self.myFoldersTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
}
delete.backgroundColor = UIColor.redColor()
let details = UITableViewRowAction(style: .Normal, title: "Edit") { (action: UITableViewRowAction, indexPath: NSIndexPath) -> Void in
let tmpFolder = self.fetchedResultController.objectAtIndexPath(indexPath) as! Folder
let destination = self.storyboard?.instantiateViewControllerWithIdentifier("editFolder") as! EditFolderViewController
destination.folder = tmpFolder
let navigationController = self.parentViewController as! UINavigationController
var response: Bool = true
if( tmpFolder.isprotected == true){
let alert = UIAlertController(title: "Password Validation", message: "Please enter the folder password", preferredStyle: .Alert)
//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
textField.text = ""
})
alert.addAction(UIAlertAction(title: "Login", style: .Default, handler: { (action) -> Void in
let textField = alert.textFields![0]
if (tmpFolder.password == textField.text){
response = true
} else {
let wrongPasswordAlert = UIAlertController(title: "Error", message: "Invalid password.", preferredStyle: UIAlertControllerStyle.Alert)
let dismiss = UIAlertAction(title: "Dismiss", style: .Default) { (alertAction: UIAlertAction) ->
Void in
}
wrongPasswordAlert.addAction(dismiss)
self.presentViewController(wrongPasswordAlert, animated: true, completion: nil)
response = false
} // else if (folder.password == textField.text)
}))
// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)
}
// 4. Present the alert.
if(response){
navigationController.pushViewController(destination, animated: true)
}
//navigationController.presentViewController(destination, animated: true, completion: nil)
//self.showDetailViewController(destination, sender: self)
}
details.backgroundColor = UIColor.grayColor()
return [delete,details]
}
// Override to support rearranging the table view.
//override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
//
//}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
myFoldersTableView.reloadData()
}
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier=="listOcassions"){
let ocassions = segue.destinationViewController as! DatesViewController
let folder = fetchedResultController.objectAtIndexPath(self.selectedRowIndex!) as! Folder
ocassions.folder = folder
}
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
var response: Bool = true
if identifier == "listOcassions" {
self.selectedRowIndex = myFoldersTableView.indexPathForSelectedRow
let folder = fetchedResultController.objectAtIndexPath(self.selectedRowIndex!) as! Folder
if( folder.isprotected == true){
let alert = UIAlertController(title: "Password Validation", message: "Please enter the folder password", preferredStyle: .Alert)
//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
textField.text = ""
})
alert.addAction(UIAlertAction(title: "Login", style: .Default, handler: { (action) -> Void in
let textField = alert.textFields![0]
if (folder.password == textField.text){
response = true
self.performSegueWithIdentifier("listOcassions", sender: self)
} else {
let wrongPasswordAlert = UIAlertController(title: "Error", message: "Invalid password.", preferredStyle: UIAlertControllerStyle.Alert)
let dismiss = UIAlertAction(title: "Dismiss", style: .Default) { (alertAction: UIAlertAction) ->
Void in
}
wrongPasswordAlert.addAction(dismiss)
self.presentViewController(wrongPasswordAlert, animated: true, completion: nil)
response = false
} // else if (folder.password == textField.text)
}))
// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)
} //if folder.isprotected == true
}
return response
}
}
I can add records but when I try to delete the record I get the following error message:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete row 0 from section 0 which only contains 0 rows before the update'
I know there are similar questions like this before but none of the answers for those questions (that i have applied and some of them are in the copied code) did not solve my issue.
Thanks a lot in advance.
Julio.

The deleteObject in your commitEditingStyle: method triggers the FRC delegate methods, which then delete the relevant row from the table view. So you can delete this line:
self.myFoldersTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
from the commitEditingStyle method - it is effectively deleting the same row twice. Hence the error.
Likewise for editActionsForRowAtIndexPath.

Related

Can't reload UITableView

I am trying to design View where i can show elements in sync with my Firebase Database. Every time element in my array changes it gets duplicated. Tried to use
self.tableView.reloadData()
but nothing changes. Tried as well
self.tableView.beginUpdates()
self.tableView.reloadRowsAtIndexPaths(NSArray.init(object: indexPath) as! [NSIndexPath], withRowAnimation: .Automatic)
self.tableView.endUpdates()
and it didn't work as previously.
I have tried unsuccesfully to perform reloading tableView in main thread using function
performSelectorOnMainThread
I am posting my code for you guys so someone can help me. Im quite new to iOS programming and i can't figure out when to reload data in tableView. Even after reading Apple's Documentation.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let alert = UIAlertController(title: "Akcja", message: "Wybierz akcję", preferredStyle: .ActionSheet)
let changeFieldNumberAction = UIAlertAction(title: "Zmień numer boiska", style: .Default, handler: {(action) in
self.showAlertOfChangingFieldNumber(indexPath)
})
let sendToRefereeAction = UIAlertAction(title: "Wskaż sędziego", style: .Default, handler: {(action) in
//self.championshitTournamentMode = false
})
let cancelAction = UIAlertAction(title: "Anuluj", style: .Cancel, handler: nil)
alert.addAction(cancelAction)
alert.addAction(changeFieldNumberAction)
alert.addAction(sendToRefereeAction)
self.presentViewController(alert, animated: true, completion: nil)
}
func showAlertOfChangingFieldNumber(indexPath: NSIndexPath) {
let fieldNumberAlert = UIAlertController(title: "Numer boiska", message: "Wpisz numer boiska", preferredStyle: .Alert)
fieldNumberAlert.addTextFieldWithConfigurationHandler({(textField: UITextField!) -> Void in
textField.placeholder = "Numer boiska"
textField.keyboardType = UIKeyboardType.NumberPad
})
let saveAction = UIAlertAction(title: "Zapisz", style: .Default, handler: {(action) -> Void in
let fieldNumberTextField = fieldNumberAlert.textFields![0] as UITextField
let fieldNumber = Int(fieldNumberTextField.text!)
self.updateGameFieldNumber(fieldNumber!, indexPath: indexPath)
})
let cancelAction = UIAlertAction(title: "Anuluj", style: .Cancel, handler: nil)
fieldNumberAlert.addAction(cancelAction)
fieldNumberAlert.addAction(saveAction)
self.presentViewController(fieldNumberAlert, animated: true, completion: nil)
}
func updateGameFieldNumber(fieldNumber: Int, indexPath: NSIndexPath){
let gameKey = games[indexPath.row].key
let ref = FIRDatabase.database().reference().child("games").child(gameKey)
games[indexPath.row].fieldNumber = fieldNumber
ref.updateChildValues(games[indexPath.row].toAnyObject() as! [NSObject : AnyObject])
//self.games.removeAtIndex(indexPath.row+1)
self.tableView.beginUpdates()
self.tableView.reloadRowsAtIndexPaths(NSArray.init(object: indexPath) as! [NSIndexPath], withRowAnimation: .Automatic)
self.tableView.endUpdates()
}
And my tableView delegate functions and function made for filling my array based on Firebase's database looks like that:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! GameViewCellTableViewCell
if games[indexPath.row].fieldNumber == 0 {
cell.fieldNumberLabel.text = "-"
} else {
cell.fieldNumberLabel.text = String(games[indexPath.row].fieldNumber)
}
cell.firstParticipantLabel.text = games[indexPath.row].firstParticipant
cell.secondParticipantLabel.text = games[indexPath.row].secondParticipant
cell.gameImage.image = UIImage(named: "tenisBall")
if games[indexPath.row].completed != true {
cell.backgroundColor = UIColor.init(red: 1, green: 109.0/255, blue: 95.0/255, alpha: 1)
} else {
cell.backgroundColor = UIColor.init(red: 160/255, green: 1, blue: 86/255, alpha: 1)
}
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.games.count
}
func getGames() {
let ref = FIRDatabase.database().reference().child("games")
ref.observeEventType(.Value, withBlock: {snapshot in
for item in snapshot.children {
let gameItem = GameItem(snapshot: item as! FIRDataSnapshot)
if(gameItem.tournamentName == self.tournamentName) {
self.games.append(gameItem)
}
}
self.tableView.reloadData()
})
}
It gets duplicated because instead of updating the value in your "games" array, you append the modified value to the array. This happens in the "getgames()" method.
inside the
func getGames()
after
self.games.append(gameItem)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})

how to get data to save to specific category in tableview instead on all categories?

I have a groceryList app
when you add an item to the category list it adds to the entire list of categories when is should not!
https://github.com/mrbryankmiller/Grocery-TableView-.git
class GroceryItemsTableViewController: UITableViewController {
//var groceryItem = ["Item1", "Item2", "Item3"]
//var groceryList = ["Breakfast","Lunch", "Dinner"]
#IBOutlet var groceryItemTableView: UITableView!
#IBAction func addGroceryItemButtonPressed(sender: UIBarButtonItem) {
///new way///
let alertController: UIAlertController = UIAlertController(title: "Add Grocery Item", message: "", preferredStyle: .Alert)
//Cancel Button
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//cancel code
}
alertController.addAction(cancelAction)
let saveAction: UIAlertAction = UIAlertAction(title: "Save", style: .Default) { action -> Void in
let textField = alertController.textFields![0]
groceryItem.items.append(textField.text!)
self.tableView.reloadData()
}
alertController.addAction(saveAction)
//Add text field
// alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
// textField.textColor = UIColor.blackColor()
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
textField.placeholder = "Enter an Item"
//alertController.textFields
}
//Present the AlertController
self.presentViewController(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//self.navigationItem.leftBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 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 groceryItem.items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("groceryItem1", forIndexPath: indexPath)
cell.textLabel!.text = groceryItem.items [indexPath.row]
return cell
}
}
If you see carefully the declaration of your class groceryItem you have a static array of elements for every item in your grocery list so every time you add a new element it's shared among all the grocery items.
Instead you should have for each grocery item a list associated with each of its items.
You could define a new struct to save for each grocery item its list of item associated like in the following way:
struct GroceryItem {
var name: String
var items: [String]
}
The we are going to change a little the code in your GroceryListTableViewController to refactor the code according your new model, so it should be like the following:
GroceryListTableViewController:
class GroceryListTableViewController: UITableViewController, GroceryItemsTableViewControllerProtocol {
var groceryList = [GroceryItem]()
#IBAction func addButton(sender: UIBarButtonItem) {
let alertController: UIAlertController = UIAlertController(title: "Add Grocery Category", message: "", preferredStyle: .Alert)
//Cancel Button
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//cancel code
}
alertController.addAction(cancelAction)
let saveAction: UIAlertAction = UIAlertAction(title: "Save", style: .Default) { action -> Void in
let textField = alertController.textFields![0]
self.groceryList.append(GroceryItem(name: textField.text!, items: [String]()))
self.tableView.reloadData()
}
alertController.addAction(saveAction)
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
textField.placeholder = "Enter an Item"
//alertController.textFields
}
//Present the AlertController
self.presentViewController(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//edit button
self.navigationItem.leftBarButtonItem = self.editButtonItem()
groceryList.append(GroceryItem(name: "Breakfast", items: ["Item1", "Item2", "Item3"]))
groceryList.append(GroceryItem(name: "Lunch", items: ["Item1", "Item2", "Item3"]))
groceryList.append(GroceryItem(name: "Dinner", items: ["Item1", "Item2", "Item3"]))
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groceryList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("prototype1", forIndexPath: indexPath) as UITableViewCell
cell.textLabel!.text = groceryList [indexPath.row].name
return cell
}
// pass a tableview cell value to navigationBar title in swift//
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destinationVC = segue.destinationViewController as! GroceryItemsTableViewController
let cell = sender as! UITableViewCell
let idx = self.tableView.indexPathForSelectedRow?.row
destinationVC.delegate = self
destinationVC.itemList = groceryList[idx!].items
destinationVC.navigationItem.title = cell.textLabel?.text
}
func didAddGroceryItem(itemName: String) {
let idx = self.tableView.indexPathForSelectedRow?.row
groceryList[idx!].items.append(itemName)
}
func didRemoveGroceryItem(index: Int) {
let idx = self.tableView.indexPathForSelectedRow?.row
groceryList[idx!].items.removeAtIndex(index)
}
}
In the above I have refactored all the code regarding the new model, I put only the places where the code change the rest keep the same.
The thing you need to pass the item associated with the cell selected to the another UIViewController and you can do it very easily in your prepareForSegue. For that we need to get the index for the selected cell and pass the elements to the another UIViewController where we have a new array of [String] created as data source to show the items.
The another important point in the code is that the GroceryListTableViewController now implements a new protocol called GroceryItemsTableViewControllerProtocol. This protocol it's the way to notify to GroceryListTableViewController from the GroceryItemsTableViewController every time a new item is added to the list it's called the delegate pattern.
GroceryItemsTableViewController:
protocol GroceryItemsTableViewControllerProtocol: class {
func didAddGroceryItem(itemName: String)
func didRemoveGroceryItem(index: Int)
}
class GroceryItemsTableViewController: UITableViewController {
weak var delegate: GroceryItemsTableViewControllerProtocol?
var itemList: [String]!
#IBAction func addGroceryItemButtonPressed(sender: UIBarButtonItem) {
///new way///
let alertController: UIAlertController = UIAlertController(title: "Add Grocery Item", message: "", preferredStyle: .Alert)
//Cancel Button
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//cancel code
}
alertController.addAction(cancelAction)
let saveAction: UIAlertAction = UIAlertAction(title: "Save", style: .Default) { [weak self] action -> Void in
guard let s = self else { return }
let textField = alertController.textFields![0]
s.itemList.append(textField.text!)
s.delegate?.didAddGroceryItem(textField.text!)
s.tableView.reloadData()
}
alertController.addAction(saveAction)
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
textField.placeholder = "Enter an Item"
//alertController.textFields
}
//Present the AlertController
self.presentViewController(alertController, animated: true, completion: nil)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("groceryItem1", forIndexPath: indexPath)
cell.textLabel!.text = itemList[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
itemList.removeAtIndex(indexPath.row)
delegate?.didRemoveGroceryItem(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
}
EDIT:
To handle properly the deletion you should create a new delegate method no notify the GroceryListTableViewController that a item has been deleted and then delete it properly and you can see in the updated code above.
I hope this help you.

Firebase Data not showing in TableView

So basically I want to get the data from Firebase and put it in the tableView and then when a cell is deleted I want to remove the data from firebase and the table view...but with my code the data is NOT even showing up in the TableView and i really don't know what's wrong...?
Here's my Database structure if it helps:
Structure
I put the data in Courses then a childByAutoId which contains CourseName,AmountOfHoles and AddedDate then get it back in a snapshot, store the snapshot in an array called courses and then get the variables for the cell in cellForRowAtIndexPath but somehow the cell is not showing on the tableView...then I would delete the cell and data in commitEditingStyle but it doesn't even get to that because the cells don't show up...
I'm new to StackOverflow, so please excuse me if something seems stupid or wrong ...dont bother to tell me tho..
class CoursesViewController: UITableViewController {
var ref = FIRDatabaseReference.init()
override func viewDidLoad() {
ref = FIRDatabase.database().reference()
tableView.allowsMultipleSelectionDuringEditing = false
//let a = ref.childByAutoId()
//a.setValue("hi")
}
var courses: [FIRDataSnapshot]! = []
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let CoursesRef = ref.child("Courses")
CoursesRef.observeEventType(.ChildAdded, withBlock: { snapshpt in
self.courses.append(snapshpt)
})
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.courses.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
let cell: UITableViewCell! = self.tableView .dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath)
let courseSnap: FIRDataSnapshot! = self.courses[indexPath.row]
let course = courseSnap.value
let coursename = course?.objectForKey("CourseName") as! String
let amountofholes = course?.objectForKey("AmountOfHoles") as! String
let addeddate = course?.objectForKey("AddedDate") as! String
cell.textLabel?.text = coursename + " " + amountofholes + " Holes"
cell.detailTextLabel?.text = addeddate
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Find the snapshot and remove the value
let courseitem = courses[indexPath.row]
courseitem.ref.removeValue()
}
}
#IBAction func addButtonDidTouch(sender: AnyObject) {
// Alert View for input
let alert = UIAlertController(title: "Course Item",message: "Add Course",preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save", style: .Default) { (action: UIAlertAction) -> Void in
//Get Date String
let date = NSDate()
print(date)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy 'at' HH:mm"
let dateString = dateFormatter.stringFromDate(date)
print(dateString)
//
let courseField = alert.textFields![0]
let holesField = alert.textFields![1]
let Courses = self.ref.child("Courses").childByAutoId()
let course = ["AddedDate": dateString as AnyObject,
"CourseName": courseField.text as! AnyObject,
"AmountOfHoles": holesField.text as! AnyObject]
Courses.setValue(course)
}
//Cancel
let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction) -> Void in
}
//TextField placeholder in alert
alert.addTextFieldWithConfigurationHandler {
(courseField: UITextField!) -> Void in
courseField.placeholder = "Course Name"
}
alert.addTextFieldWithConfigurationHandler {
(holesField: UITextField!) -> Void in
holesField.placeholder = "Holes (6/9/18)"
}
//Add alert
alert.addAction(saveAction)
alert.addAction(cancelAction)
presentViewController(alert, animated: true, completion: nil)
}
}
Man you have to insert your code when a snapshot is found out !
I think you can go like this :
CoursesRef.observeEventType(.ChildAdded, withBlock: { snapshot in
self.courses.append(snapshot)
self.yourTable.insertRowsAtIndexPaths([NSIndexPath(forRow: self.courses.count-1, inSection: 0)], withRowAnimation: .Bottom)
})
check with this code
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(self.courses.count > 0){
tablecount = self.courses.count
} else {
tablecount = 0
self.table.reloaddata()
}
return tablecount
}

two table views in one viewcontroller swift

I'm trying to make a pros and cons list in swift, but whenever I delete a con it deletes a pro. I think that it is a problem with index path being linked to both the pros and cons view controller but I don't know how or where I can separate them
class prosConsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
#IBOutlet var prosTableViewOutlet: UITableView!
#IBOutlet var consTableViewOutlet: UITableView!
#IBOutlet var tableViewOutlet: UITableView!
var colleges : [NetCollege] = []
#IBOutlet var consTableView: UITableView!
var collegesTwo : [NetCollegeTwo] = []
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if tableView == tableViewOutlet
{
return colleges.count
}
else
{
return collegesTwo.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
if tableView == tableViewOutlet
{
let cell = tableViewOutlet.dequeueReusableCellWithIdentifier("cellID") as! tableViewCell
//the line under maybe?
let college = colleges[indexPath.row]
cell.textLabel?.text = college.name
return cell
}
else
{
let cellTwo = consTableView.dequeueReusableCellWithIdentifier("IDCell") as! tableViewCell
let collegeTwo = collegesTwo[indexPath.row]
cellTwo.textLabel?.text = collegeTwo.conName
return cellTwo
}
}
override func viewDidLoad()
{
super.viewDidLoad()
editButtonItem().tag = 0
func shouldAutorotate() -> Bool {
return false
}
func supportedInterfaceOrientations() -> Int {
return UIInterfaceOrientation.LandscapeRight.rawValue
}
}
#IBAction func plusButtonTwo(sender: UIBarButtonItem)
{
let alertTwo = UIAlertController(title: "Add Con", message: nil, preferredStyle: .Alert)
alertTwo.addTextFieldWithConfigurationHandler
{ (textField) -> Void in
textField.placeholder = "Add Con Here"
}
let cancelActionTwo = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alertTwo.addAction(cancelActionTwo)
let addActionTwo = UIAlertAction(title: "Add", style: .Default) { (action) -> Void in
let addCollegesTextFieldTwo = (alertTwo.textFields?[0])! as UITextField
let netCollegeTwo = NetCollegeTwo(nameTwo: addCollegesTextFieldTwo.text!)
self.collegesTwo.append(netCollegeTwo)
self.consTableView.reloadData()
}
alertTwo.addAction(addActionTwo)
self.presentViewController(alertTwo, animated: true, completion: nil)
}
#IBAction func onTappedPlusButton(sender: UIBarButtonItem)
{
let alert = UIAlertController(title: "Add Pro", message: nil, preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler
{ (textField) -> Void in
textField.placeholder = "Add Pro Here"
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(cancelAction)
let addAction = UIAlertAction(title: "Add", style: .Default) { (action) -> Void in
let addCollegesTextField = (alert.textFields?[0])! as UITextField
let netCollege = NetCollege(name: addCollegesTextField.text!)
self.colleges.append(netCollege)
self.tableViewOutlet.reloadData()
}
alert.addAction(addAction)
self.presentViewController(alert, animated: true, completion: nil)
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == UITableViewCellEditingStyle.Delete
{
colleges.removeAtIndex(indexPath.row)
tableViewOutlet.reloadData()
}
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
If you want to implement all this in one view controller, you can try this:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == UITableViewCellEditingStyle.Delete
{
if tableView == tableViewOutlet
{
colleges.removeAtIndex(indexPath.row)
tableView.reloadData()
}
else
{
collegesTwo.removeAtIndex(indexPath.row)
tableView.reloadData()
}
}
}
But in this case better solution would be to create two classes called like DataSourceOne, DataSourceTwo (or TableViewModelOne, TableViewModelTwo), and implement all related logic there. This even could be two instances of just one class DataSource, depending on what exactly you need. Then you can instantiate those helper classes in viewDidLoad and assign them to dataSource and delegate properties of your table views. Your will also need to hold strong reference for them somewhere, because dataSource and delegate properties are week.

Swift - UITableView won't add data

I have a UITableView and when I add data, it will only allow me to add one row in the UITableview even though I return goals.count for the amount of rows.
This is what I have.
#IBAction func myAddGoal(sender: AnyObject) {
let ac = UIAlertController(title: "Enter a Goal", message: "It can be anything you want!", preferredStyle: .Alert)
ac.addTextFieldWithConfigurationHandler(nil)
let submit = UIAlertAction(title: "Submit", style: .Default) { [unowned self, ac] (action: UIAlertAction!) in
let goal = ac.textFields![0] as UITextField
self.submitGoal(goal.text)
}
ac.addAction(submit)
ac.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Destructive, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
func submitGoal(goal: String){
if goal == "" {
println("textfield is empty")
} else {
goals.insert(goal, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
myTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
println(goals)
}
}
I am able to add only ONE goal and it will animate into the UITableView. If I want to add another goal, it will not let me. The app crashes when I hit submit for a second goal entry.
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return goals.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let object = goals[indexPath.row]
cell.textLabel!.text = object
mySwitch.on = false
mySwitch.tag = indexPath.row as Int
mySwitch.addTarget(self, action: "UISwitchUpdated", forControlEvents: UIControlEvents.TouchUpInside)
cell.selectionStyle = .None
cell.accessoryView = mySwitch
return cell
}

Resources