I'm having trouble getting the text from a UISearchBar - ios

i tried to put searchBar above my table but code not worked with me
import UIKit
import CoreData
class ToDoListViewController: UITableViewController {
var itemArray = [Item]()
var selectedCategory : Category?{
didSet {
loadItems()
}
}
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
}
// MARK - Table View DataSource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
let item = itemArray[indexPath.row]
cell.textLabel?.text = item.title
cell.accessoryType = item.done ? .checkmark : .none
return cell
}
// MARK - Table View Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
itemArray[indexPath.row].done = !itemArray[indexPath.row].done
saveItems()
tableView.deselectRow(at: indexPath, animated: true)
}
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New To Do List Item", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Item", style:.default) { (action) in
// This will happend when the user clicks the Add Item on our add UIAlert
let newItem = Item(context: self.context)
newItem.title = textField.text!
newItem.done = false
newItem.parentCategory = self.selectedCategory
self.itemArray.append(newItem)
self.saveItems()
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Create New Item"
textField = alertTextField }
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
//MARK: - Data Manipulation Methods
func saveItems(){
do {
try context.save()
} catch {print("Error saving context \(error)") }
self.tableView.reloadData()
}
func loadItems(with request: NSFetchRequest<Item> = Item.fetchRequest(), with predicate: NSPredicate? = nil){
let categoryPredicate = NSPredicate(format: "parentCategory.name MATCHES %#", selectedCategory!.name!)
if let addtionalPredicate = predicate {
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [categoryPredicate,addtionalPredicate])
}else {
request.predicate = categoryPredicate
}
do {
itemArray = try context.fetch(request)
} catch { print("Error fetching data from request\(error)")
tableView.reloadData()
}
}
}
// MARK: - Search Bar Methods
extension ToDoListViewController : UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
let request : NSFetchRequest<Item> = Item.fetchRequest()
let predicate = NSPredicate(format: "title CONTAINS[cd] %#", searchBar.text!)
request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]
loadItems(with: request, with: predicate)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text?.count == 0 {
loadItems()
DispatchQueue.main.async {
searchBar.resignFirstResponder()
}
}
}
}

The problem with Do-Catch
the Solution should be
do {
itemArray = try context.fetch(request)
} catch { print("Error fetching data from request\(error)")
}
tableView.reloadData()

Related

Sending selected URLS with SMTP (Swift)

I have tableview listed pdfs by retrieving from Firebase. No problem with retrieving datas and sending default SMTP. What I am trying to do that selected urls(pdf) in tableview, will be sent by using SMTP to user email so that user can easily reach pdf urls. I could not figure out how to handle it. This is the only critical point in my project. Any help is appreciated.
import UIKit
import Firebase
import PDFKit
import skpsmtpmessage
class IcsViewcontroller: UIViewController , UISearchBarDelegate,SKPSMTPMessageDelegate{
var preImage : UIImage?
let cellSpacingHeight: CGFloat = 20
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var pdfListView: UITableView!
#IBOutlet weak var spinner: UIActivityIndicatorView!
var pdfList = [pdfClass]()
var searchall = [pdfClass]()
var searching = false
var selectedPdf = [pdfClass]()
override func viewDidLoad() {
super.viewDidLoad()
let editButton = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(showEditing(_:)))
navigationItem.rightBarButtonItem = editButton
pdfListView.delegate = self
pdfListView.dataSource = self
searchBar.delegate = self
self.pdfListView.isHidden = true
getPdf()
sendEmail()
searchBar.searchTextField.backgroundColor = .white
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let selectionIndexPath = self.pdfListView.indexPathForSelectedRow {
self.pdfListView.deselectRow(at: selectionIndexPath, animated: animated)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if searching {
let destination = segue.destination as! PdfKitViewController
let selectedIndexPath = pdfListView.indexPathForSelectedRow
destination.pdf = searchall[selectedIndexPath!.row]
} else {
let destination = segue.destination as! PdfKitViewController
let selectedIndexPath = pdfListView.indexPathForSelectedRow
destination.pdf = pdfList [selectedIndexPath!.row]
}
}
#objc func showEditing(_ sender: UIBarButtonItem)
{
if(self.pdfListView.isEditing == true)
{
self.pdfListView.isEditing = false
self.navigationItem.rightBarButtonItem?.title = "Edit"
}
else
{
self.pdfListView.allowsMultipleSelectionDuringEditing = true
self.pdfListView.isEditing = true
self.navigationItem.rightBarButtonItem?.title = "Done"
}
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
if searchBar.text == nil || searchBar.text == "" {
searching = false
} else {
searching = true
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searching = false
searchBar.text = ""
self.pdfListView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searching = false
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
searchall = pdfList
searching = false
pdfListView.reloadData()
} else {
searching = true
searchall = pdfList.filter({($0.pdf_name?.lowercased().prefix(searchText.count))! == searchText.lowercased() })
pdfListView.reloadData()
}
}
func getPdf () {
spinner.startAnimating()
let docRef = Storage.storage().reference().child("ICS_Documents")
docRef.listAll{ (result , error ) in
if error != nil {
let alert = UIAlertController(title: "Error", message: "No Database Connection", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
self.spinner.stopAnimating()
}
for item in result.items {
let storeageLocation = String( describing : item)
let gsReference = Storage.storage().reference(forURL: storeageLocation)
gsReference.downloadURL{ url , error in
if let error = error{
print(error)
} else {
let pdf_name = String( item.name)
let pdf_url = url?.absoluteString
let thumbnailSize = CGSize(width: 100, height: 100)
let thmbnail = self.generatePdfThumbnail(of: thumbnailSize, for: url!, atPage: 0)
let pdfall = pdfClass(pdf_name: pdf_name, pdf_url: pdf_url!, pdf_preview: thmbnail!)
self.pdfList.append(pdfall)
}
DispatchQueue.main.async {
self.pdfList.sort{ $0.pdf_name ?? "" < $1.pdf_name ?? ""}
self.pdfListView.reloadData()
self.spinner.stopAnimating()
self.pdfListView.isHidden = false
}
}
}
}
}
func generatePdfThumbnail(of thumbnailSize: CGSize , for documentUrl: URL, atPage
pageIndex: Int) -> UIImage? {
let pdfDocument = PDFDocument(url: documentUrl)
let pdfDocumentPage = pdfDocument?.page(at: pageIndex)
return pdfDocumentPage?.thumbnail(of: thumbnailSize, for:
PDFDisplayBox.trimBox)
}
func sendEmail() {
let message = SKPSMTPMessage()
message.relayHost = "smtp.gmail.com"
message.login = "xxx#gmail.com"
message.pass = "******"
message.requiresAuth = true
message.wantsSecure = true
message.relayPorts = [587]
message.fromEmail = "xxxx#gmail.com"
message.toEmail = "xxxx#gmail.com"
message.subject = "subject"
let messagePart = [kSKPSMTPPartContentTypeKey: "text/plain; charset=UTF-8",
kSKPSMTPPartMessageKey: "Hi alll"]
message.parts = [messagePart]
message.delegate = self
message.send()
}
func messageSent(_ message: SKPSMTPMessage!) {
print("Successfully sent email!")
}
func messageFailed(_ message: SKPSMTPMessage!, error: Error!) {
print("Sending email failed!")
}
}
extension IcsViewcontroller : UITableViewDelegate,UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if searching{
return searchall.count
}else {
return pdfList.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "pdfCell", for: indexPath) as! pdfCellTableViewCell
let varcell : pdfClass
if searching {
varcell = searchall [indexPath.row]
} else {
varcell = pdfList [indexPath.row]
}
cell.configure(name: varcell.pdf_name! , pdfthumbnail: varcell.pdf_preview!)
cell.accessoryType = .disclosureIndicator
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var indx : pdfClass
if searching{
indx = searchall[indexPath.row ]
}else {
indx = pdfList[indexPath.row]
}
self.selectdeselectcell(tableview: tableView, indexpath: indexPath)
print("selected")
if pdfListView.isEditing {
func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
return !tableView.isEditing
}
}else{
performSegue(withIdentifier: "toPdfKit", sender: indx)
print(indexPath.row)
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.selectdeselectcell(tableview: tableView, indexpath: indexPath)
print("deselected")
}
func selectdeselectcell(tableview : UITableView ,indexpath : IndexPath){
if pdfListView.isEditing{
self.selectedPdf.removeAll()
if let arr = pdfListView.indexPathForSelectedRow{
print(arr)
}
}else {
return
}
}
/* func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action:UITableViewRowAction,indexPath:IndexPath)-> Void in
let storage = Storage.storage()
var childsURL : String
if self.searching {
childsURL = self.searchall[indexPath.row ].pdf_url!
}else{
childsURL = self.pdfList[indexPath.row].pdf_url!
}
let storageref = storage.reference(forURL: childsURL)
storageref.delete{ error in
if let error = error {
print(error.localizedDescription)
} else{
print("File deleted")
}
}
self.pdfList.removeAll()
self.getPdf()
})
return [deleteAction]
}*/
}

Implementing a UISearchController on top of UITableView displaying Core Data in swift 5

I have a core data Swift master/detail view application (code is located here) where the core data object, called sweetnote, is basically this:
class sweetnote: NSObject {
private(set) var noteId : UUID
private(set) var noteTitle : String
private(set) var noteText : NSAttributedString
private(set) var noteCreated : Int64
private(set) var noteModified : Int64
private(set) var noteCategory : String
}
I have a Master view controller which renders these notes in a UITableView with the help of a function in Helpers/sweetnoteCoreDataHelper.swift called readNotesFromCoreData:
static func readNotesFromCoreData(fromManagedObjectContext: NSManagedObjectContext) -> [sweetnote] {
var returnedNotes = [sweetnote]()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Note")
fetchRequest.predicate = nil
do {
let fetchedNotesFromCoreData = try fromManagedObjectContext.fetch(fetchRequest)
fetchedNotesFromCoreData.forEach { (fetchRequestResult) in
let noteManagedObjectRead = fetchRequestResult as! NSManagedObject
returnedNotes.append(sweetnote.init(
noteId: noteManagedObjectRead.value(forKey: "noteId") as! UUID,
noteTitle: noteManagedObjectRead.value(forKey: "noteTitle") as! String,
noteText: noteManagedObjectRead.value(forKey: "noteText") as! NSAttributedString,
noteCreated: noteManagedObjectRead.value(forKey: "noteCreated") as! Int64,
noteModified: noteManagedObjectRead.value(forKey: "noteModified") as! Int64,
noteCategory: noteManagedObjectRead.value(forKey: "noteCategory")
as! String))
}
} catch let error as NSError {
// TODO error handling
print("Could not read notes from core data. \(error), \(error.userInfo)")
}
// Set note count
self.count = returnedNotes.count
// Sort by modified date
return returnedNotes.sorted() {
$0.noteModified > $1.noteModified
}
}
And then in my Master view controller (at UI/MasterViewController.swift) I have a UISearchController configured at the top of the UITableView which is currently not applying any filtering logic based on the text and I'm having trouble determining where I need to update:
import UIKit
import Foundation
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
var detailViewController: DetailViewController? = nil
var searchtemplate: String? {didSet {print (searchtemplate as Any)}}
// Search results controller
let resultSearchController = UISearchController(searchResultsController: nil)
var sweetnotes: [sweetnote] = []
var searchResults: [sweetnote] = []
override func viewDidLoad() {
super.viewDidLoad()
// Core data initialization
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
// Create alert controller
let alert = UIAlertController(
title: "Could note get app delegate",
message: "Could note get app delegate, unexpected error occurred. Try again later.",
preferredStyle: .alert)
// Add OK action
alert.addAction(UIAlertAction(title: "OK",
style: .default))
// Show alert
self.present(alert, animated: true)
return
}
// Pass the context forward from the app delegate
let managedContext = appDelegate.persistentContainer.viewContext
// Set context in the storage
sweetnoteStorage.storage.setManagedContext(managedObjectContext: managedContext)
// Set the search controller programmatically
resultSearchController.searchResultsUpdater = self
resultSearchController.hidesNavigationBarDuringPresentation = false
resultSearchController.obscuresBackgroundDuringPresentation = false
self.definesPresentationContext = true
// Scope bar
//resultSearchController.searchBar.scopeButtonTitles = ["All", "Ideas", "Information", "Lifestyle", "Lists", "Recipes", "Other"]
//searchView.addSubview(resultSearchController.searchBar)
tableView.tableHeaderView = resultSearchController.searchBar
resultSearchController.searchBar.tintColor = UIColor.darkGray
resultSearchController.searchBar.barTintColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 0.8)
resultSearchController.searchBar.placeholder = "Search sweetnotes"
// Prefer large titles
self.navigationController?.navigationBar.prefersLargeTitles = true
// Edit-note button
navigationItem.leftBarButtonItem = editButtonItem
// Add-note button
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
navigationItem.rightBarButtonItem = addButton
if let split = splitViewController {
let controllers = split.viewControllers
detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
self.tableView.delegate = self
}
...
override func viewWillAppear(_ animated: Bool) {
clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
// Dismiss search bar on scroll-down
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
resultSearchController.dismiss(animated: false, completion: nil)
}
#objc
func insertNewObject(_ sender: Any) {
performSegue(withIdentifier: "showCreateNoteSegue", sender: self)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
//let object = objects[indexPath.row]
let object = sweetnoteStorage.storage.readNote(at: indexPath.row)
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
//controller.detailItem = resultSearchController.isActive ? searchResults[indexPath.row] : sweetnotes[indexPath.row]
}
}
}
// MARK: - Table View
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
}
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else { return }
print(text)
}
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
searchtemplate = searchText
tableView.reloadData()
}
func updateSearchResultsForSearchController(searchController: UISearchController, fromManagedObjectContext: NSManagedObjectContext) {
let searchText = searchController.searchBar.text!
let predicate = NSPredicate(format: "%K CONTAINS[c] %#", argumentArray: ["noteText", searchText])
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Note")
fetchRequest.predicate = predicate
do {
let fetchedNotesFromCoreData = try fromManagedObjectContext.fetch(fetchRequest)
fetchedNotesFromCoreData.forEach { (fetchRequestResult) in
let noteManagedObjectRead = fetchRequestResult as! NSManagedObject
searchResults.append(sweetnote.init(
noteId: noteManagedObjectRead.value(forKey: "noteId") as! UUID,
noteTitle: noteManagedObjectRead.value(forKey: "noteTitle") as! String,
noteText: noteManagedObjectRead.value(forKey: "noteText") as! NSAttributedString,
noteCreated: noteManagedObjectRead.value(forKey: "noteCreated") as! Int64,
noteModified: noteManagedObjectRead.value(forKey: "noteModified") as! Int64,
noteCategory: noteManagedObjectRead.value(forKey: "noteCategory")
as! String))
}
} catch let error as NSError {
// TODO error handling
print("Could not read notes from core data. \(error), \(error.userInfo)")
}
tableView.reloadData()
}
...
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if resultSearchController.isActive && resultSearchController.searchBar.text != "" {
return searchResults.count
} else {
return sweetnoteStorage.storage.count()
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! sweetnoteUITableViewCell
//let note = fetchedResultsController.object(at: indexPath)
//configureCell(cell, withEvent: note)
if let object = sweetnoteStorage.storage.readNote(at: indexPath.row) {
cell.noteTitleLabel!.text = object.noteTitle
cell.noteTextLabel!.attributedText = object.noteText
cell.noteCategoryLabel!.text = object.noteCategory
cell.noteDateLabel!.text = sweetnoteDateHelper.convertDate(date: Date.init(minutes: object.noteModified))
}
//cell.contentView.layer.cornerRadius = 6.0
//cell.contentView.layer.borderColor = UIColor.gray.withAlphaComponent(0.5).cgColor
//cell.contentView.layer.borderWidth = 1.0
//cell.contentView.layer.masksToBounds = true
//cell.contentView.clipsToBounds = true
cell.backgroundColor = UIColor.white
cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable
if resultSearchController.isActive {
return false
} else {
return true
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
presentDeletionFailsafe(indexPath: indexPath)
//objects.remove(at: indexPath.row)
//sweetnoteStorage.storage.removeNote(at: indexPath.row)
//tableView.deleteRows(at: [indexPath], with: .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.
}
}
// Deletion failsafe function
func presentDeletionFailsafe(indexPath: IndexPath) {
let alert = UIAlertController(title: nil, message: "Are you sure you would like to delete this note?", preferredStyle: .alert)
// Delete the note
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
// replace data variable with your own data array
sweetnoteStorage.storage.removeNote(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .fade)
}
alert.addAction(yesAction)
// Cancel and don't delete note
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
func configureCell(_ cell: sweetnoteUITableViewCell, withEvent note: Note) {
cell.noteTitleLabel!.text = note.noteTitle
cell.noteTextLabel!.attributedText = note.noteText
cell.noteCategoryLabel!.text = note.noteCategory
cell.noteDateLabel!.text = sweetnoteDateHelper.convertDate(date: Date.init(minutes: note.noteModified))
}
}
The function updateSearchResultsForSearchController is where I tried to establish a predicate and execute the search result fetch request, based on some similar questions out there where people implemented search controllers on top of core data projects, but I am definitely still missing something or am in the wrong place because when text is entered to the search bar, all notes remain in the table view.
Any answers/suggestions are massively appreciated as I've spent a good deal of time on this. I am happy to provide more information and context if that helps you out. And again the code is located in my 'searchbar' branch of my project at here. Thank you very much in advance.

Any idea as to why my predicate keeps returning nil and crashing my app

Whenever I run my code and click on a category, my app crashed and tells me that it found an error during the tableview reload line. error message
import UIKit
import CoreData
class HomeViewController: UIViewController {
var itemArray = [Item]()
var selectedCategory : CategoryList? {
didSet {
loadItems()
}
}
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
tableView.delegate = self
tableView.dataSource = self
navigationItem.title = "To Do List"
}
#IBAction func addItem(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add a New Task", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Item", style: .default) { (action) in
//what will happen once the user clicks the Add item on our alert
let newItem = Item(context: self.context)
newItem.title = textField.text!
newItem.done = false
newItem.parentCategory = self.selectedCategory
self.itemArray.append(newItem)
self.saveItems()
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Create new Item"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
func saveItems() {
do {
try context.save()
} catch {
print("Error saving context \(error)")
}
self.tableView.reloadData()
}
func loadItems(with request: NSFetchRequest<Item> = Item.fetchRequest(), predicate: NSPredicate? = nil) {
let categoryPredicate = NSPredicate(format: "parentCategory.name MATCHES %#", selectedCategory!.name!)
print(categoryPredicate)
if let addtionalPredicate = predicate {
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [categoryPredicate, addtionalPredicate])
} else {
request.predicate = categoryPredicate
}
do {
itemArray = try context.fetch(request)
} catch {
print("Error fetching data from context \(error)")
}
tableView.reloadData()
}
}
extension HomeViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//print(itemArray[indexPath.row])
itemArray[indexPath.row].done = !itemArray[indexPath.row].done
saveItems()
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension HomeViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
let item = itemArray[indexPath.row]
cell.textLabel?.text = item.title
cell.accessoryType = item.done ? .checkmark : .none
return cell
}
}
//MARK: SearchBar Methods
extension HomeViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
let request : NSFetchRequest<Item> = Item.fetchRequest()
let predicate = NSPredicate(format: "title CONTAINS[cd] %#", searchBar.text!)
request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]
loadItems(with: request, predicate: predicate)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text?.count == 0 {
loadItems()
DispatchQueue.main.async {
searchBar.resignFirstResponder()
}
}
}
}

duplication using headers section in tableview using Swift

well I'm trying to add date to my header sections every time the user is done with his task. the problem is im kinda new with headers section and for some reason every time I add more than two tasks into the "Done" section, it seems like it duplicates itself.
have looked around stackOverFlow and couldn't find what I needed, and I hope u guys can help me up :)
Here's a pic of the app with the problem: https://imgur.com/wjVy9Uy
Here's my code:
import Foundation
import CoreData
import UIKit
import SwipeCellKit
protocol TaskDelegate {
func updateTaskName(name:String)
}
class TasksManViewController: UITableViewController, SwipeTableViewCellDelegate {
#IBOutlet weak var Sege: UISegmentedControl!
var tasksArray = [Task](){
didSet {
// because we perform this operation on the main thread, it is safe
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
let isSwipeRightEnabled = true
var delegate: TaskDelegate?
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
}
override func viewWillAppear(_ animated: Bool) {
loadTasks()
}
// MARK: - DataSource + Delegate Methods:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasksArray.count
}
override func numberOfSections(in tableView: UITableView) -> Int {
return tasksArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "taskCellRow") as! SwipeTableViewCell
cell.delegate = self
cell.textLabel?.text = tasksArray[indexPath.row].title
return cell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
if orientation == .left {
guard isSwipeRightEnabled else { return nil }
let doneAction = SwipeAction(style: .destructive, title: "Done") { (action, indexPath) in
//STEP1: Append the task to the doneTasksArr:
self.tasksArray[indexPath.row].isDone = true
//STEP3: Remove the Row:
self.tasksArray.remove(at: indexPath.row)
//STEP4: Update the Model:
self.saveTasks()
self.delegate?.updateTaskName(name: "")
self.tableView.reloadData()
}
let unDoneAction = SwipeAction(style: .destructive, title: "Undone") { (unDoneAction, indexPath) in
self.tasksArray[indexPath.row].isDone = false
self.tasksArray.remove(at: indexPath.row)
self.saveTasks()
}
//configure btn:
doneAction.backgroundColor = .cyan
unDoneAction.backgroundColor = .blue
if Sege.selectedSegmentIndex == 0 { //Doing this to allow the user to unDone tasks.
return [doneAction]
} else { return [unDoneAction] }
} else {
let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
self.context.delete(self.tasksArray[indexPath.row])
self.tasksArray.remove(at: indexPath.row)
self.saveTasks()
self.delegate?.updateTaskName(name: "")
self.tableView.reloadData()
}
return [deleteAction]
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - Class Methods:
#IBAction func addBtnTapped(_ sender: UIBarButtonItem) {
Sege.selectedSegmentIndex = 0 // Doing this to avoid the user to insert a task into the DoneTasks by mistake! and avoiad a bug :)
insertNewTask()
}
func insertNewTask() {
var textField = UITextField()
let alert = UIAlertController(title: "New Task", message: "Please Add Your Task", preferredStyle: .alert)
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Create New Task"
textField = alertTextField
}
let action = UIAlertAction(title: "Add", style: .default) { (action) in
let newItem = Task(context: self.context)
newItem.title = textField.text!
newItem.isDone = false
newItem.date = Date()
self.tasksArray.append(newItem)
self.delegate?.updateTaskName(name: newItem.title!)
self.saveTasks()
}
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
// MARK: - Sege Section:
#IBAction func segeControlTapped(_ sender: UISegmentedControl) {
switch Sege.selectedSegmentIndex
{
case 0:
//Loading normal tasks whose are not done
loadTasks()
case 1:
//Loading the doneTasks:
loadDoneTasksFrom()
default:
print("There's something wrong with Sege!")
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let completedTasksToDisply = 0
if Sege.selectedSegmentIndex == 1 {
if let firstTask = tasksArray[section].date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from: firstTask)
return " " + dateString + " " + " " + "Completed Tasks: \(completedTasksToDisply)"
}
}
return ""
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel?.font = UIFont(name: "Verdana", size: 13.0)
header.textLabel?.textAlignment = NSTextAlignment.center
}
//MARK: - Model Manipulation Methods:
func saveTasks() {
do {
try! context.save()
} catch let err {
print("Error Saving context \(err)")
}
}
func loadTasks() {
let request: NSFetchRequest<Task> = Task.fetchRequest()
request.predicate = NSPredicate(format: "isDone == %#", NSNumber(value: false))
request.sortDescriptors = [NSSortDescriptor(key: "isDone", ascending: false)]
do{
tasksArray = try! context.fetch(request)
} catch {
print("There was an error with loading items \(error)")
}
tableView.reloadData()
}
func loadDoneTasksFrom() {
let request:NSFetchRequest<Task> = Task.fetchRequest()
request.predicate = NSPredicate(format: "isDone == %#", NSNumber(value: true))
request.sortDescriptors = [NSSortDescriptor(key: "isDone", ascending: false)]
do{
tasksArray = try context.fetch(request)
} catch {
print("Error fetching data from context\(error)")
}
tableView.reloadData()
}
}
EDIT: Okay I see what you are trying to do. Give this a shot - we will need a double array - each array inside will have to be split by date - our query would look something like this:
var tasksArray = [[Task]]()
var sectionDates = [String]()
func loadTasks() {
tasksArray.removeAll(keepingCapacity: false)
sectionDates.removeAll(keepingCapacity: false)
let request: NSFetchRequest<Task> = Task.fetchRequest()
request.predicate = NSPredicate(format: "isDone == %#", NSNumber(value: false))
request.sortDescriptors = [NSSortDescriptor(key: "isDone", ascending: false)]
do{
let tasks = try! context.fetch(request)
for task in tasks {
if let taskDate = task.date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from: taskDate)
if self.sectionDates.contains(dateString) {
if let section = self.sectionDates.firstIndex(of: dateString) {
self.tasksArray[section].append(task)
}
} else {
self.sectionDates.append(dateString)
// EDIT - ADD THIS LINE (and self. where necessary)
self.tasksArray.append([])
if let section = self.sectionDates.firstIndex(of: dateString) {
self.tasksArray[section].append(task)
}
}
}
}
} catch {
print("There was an error with loading items \(error)")
}
tableView.reloadData()
}
Could also be helpful to load your objects in order but with this set up it should still group everything correctly regardless of the order - unless you want your sections in a specific order then you can specify in query
Now changes to your tableView delegate methods
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionDates.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasksArray[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "taskCellRow") as! SwipeTableViewCell
cell.delegate = self
cell.textLabel?.text = tasksArray[indexPath.section][indexPath.row].title
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let completedTasksToDisply = 0
if Sege.selectedSegmentIndex == 1 {
let dateString = sectionDates[section]
return " " + dateString + " " + " " + "Completed Tasks: \(completedTasksToDisply)"
}
return ""
}
I figured I'd leave the rest of the tableView delegate methods to you but for the most part we just need to identify the section before the indexPath row when working with the double array - as we did in cellForRow
I ran this code and this was the result:

How can I delete data in coreData and Tableview with one Button?

I'm actually doing an app for recipe, I already did the persistent data to save my ingredients in the list but when I want to delete my ingredients with my button it works at the first time but come back when I restart my app.
Here's my code :
class AddIngredientController: UIViewController, ShowAlert {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var ingredientsTableView: UITableView!
var itemArrayIngredient = [Item]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
print(dataFilePath)
loadItems()
}
func saveItems() {
do {
try context.save()
} catch {
print("Error saving context \(error)")
}
}
func loadItems(with request: NSFetchRequest<Item> = Item.fetchRequest()) {
do {
itemArrayIngredient = try context.fetch(request)
} catch {
print("Error fetching data from context \(error)")
}
}
#IBAction func clearButton(_ sender: UIButton) {
context.delete() //Here the problem
itemArrayIngredient.removeAll()
saveItems()
ingredientsTableView.reloadData()
}
#IBAction func addButton(_ sender: UIButton) {
if textField.text!.isEmpty {
showAlert(title: "No Ingredients", message: "Please, add some ingredients to your list.")
} else {
newIngredientAdded()
}
}
func newIngredientAdded() {
let newItem = Item(context: context)
newItem.title = textField.text!
itemArrayIngredient.append(newItem)
saveItems()
ingredientsTableView.reloadData()
textField.text! = ""
}
}
extension AddIngredientController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArrayIngredient.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customSearchCell", for: indexPath)
let item = itemArrayIngredient[indexPath.row]
cell.textLabel?.text = item.title
cell.textLabel?.textColor = UIColor.white
cell.textLabel?.font = UIFont(name: "Marker Felt", size: 19)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
saveItems()
tableView.deselectRow(at: indexPath, animated: true)
}
}
context.delete must be called with an argument. For example
#IBAction func clearButton(_ sender: UIButton) {
itemArrayIngredient.forEach { context.delete($0) }
itemArrayIngredient.removeAll()
saveItems()
ingredientsTableView.reloadData()
}
You need to delete a specific object from core data. Please refer below code
let fetchRequest = NSFetchRequest(entityName: "EntityName")
if let result = try? context.fetch(fetchRequest) {
for object in result {
//Please check before delete operation
if object.id == Your_Deleted_Object_ID{
context.delete(object)
}
}
}
You can delete all data from particular entity by using NSBatchDeleteRequest. See following code. The main advantage of NSBatchDeleteRequest is, you don't need to enumerate on array of object.
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetch)
do {
try context.execute(deleteRequest)
} catch {
print(error.localizedDescription)
}

Resources