Swift - Getting TableViewControllers to talk to one another












0















I'm working on an app which is date based. I'm trying to get information to pass from one TableViewController to another.



It's a notification based app that reminds the user that something comes out today. So on the date it comes out, I'd like it to come off the release list and go onto the released list (So if something comes out the Nov.8th, on that date it'll be moved to the released list).



I'm having trouble getting it to work. I used the below codes and the date comes and goes without anything happening, it still shows it on the release list.



I've tried several options and different variations of code but nothing seems to work.



I do have this code in the AppDelegate.Swift file so it refreshes the information:



 func applicationDidBecomeActive(_ application: UIApplication) { 


Below is the code I used on the release list:



let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date > %@", startOfToday)
fetchRequest.predicate = predicate


And here's the code on the released list:



let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date < %@", startOfToday)
fetchRequest.predicate = predicate


Here's the code for the FreshReleaseTableViewController:



import UIKit
import CoreData
import UserNotifications

class FreshReleaseTableViewController: UITableViewController{
var freshreleases = [Release_Date]()
let dateFormatter = DateFormatter()

override func viewDidLoad() {
super.viewDidLoad()

//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "Mic App Logo.png"), for: UIControlState.normal)

dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
}

@objc func editAction() {
let viewController = AddfreshreleaseViewController()
navigationController?.present(viewController, animated: true, completion: nil)
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

let fetchRequest = Release_Date.fetchRequest() as NSFetchRequest<Release_Date>

let sortDescriptor1 = NSSortDescriptor(key: "artist", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "album", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
do {
freshreleases = try context.fetch(fetchRequest)
} catch let error {
print("Could not fetch because of error: (error).")
}

let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date > %@", startOfToday)
fetchRequest.predicate = predicate

tableView.reloadData()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return freshreleases.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "FreshReleaseCellIdentifier", for: indexPath)

let freshrelease = freshreleases[indexPath.row]

cell.textLabel?.numberOfLines = 0

let artist = freshrelease.artist ?? ""
let album = freshrelease.album ?? ""
cell.textLabel?.text = artist + "'snnew album '" + album + "'nreleases"

if let date = freshrelease.release_date as Date? {
cell.detailTextLabel?.text = dateFormatter.string(from: date)
} else {
cell.detailTextLabel?.text = ""
}

return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}

// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if freshreleases.count > indexPath.row {
let freshrelease = freshreleases[indexPath.row]

// Remove notification
if let identifier = freshrelease.release_dateId {
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [identifier])
}

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(freshrelease)
freshreleases.remove(at: indexPath.row)
do {
try context.save()
} catch let error {
print("Could not save (error)")
}
tableView.deleteRows(at: [indexPath], with: .fade)
}
}

@available(iOS 11.0, *)

override func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

{
let modifyAction = UIContextualAction(style: .normal, title: "Edit", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
let MainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc : UIViewController = MainStoryboard.instantiateViewController(withIdentifier: "FreshReleaseEdit") as UIViewController
self.present(vc, animated: true, completion: nil)
success(true)

})
modifyAction.title = "Edit"
modifyAction.backgroundColor = .blue

return UISwipeActionsConfiguration(actions: [modifyAction])
}

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}


And here's the code for the ReleasedTableViewController:



import UIKit
import CoreData
import UserNotifications

class ReleasedTableViewController: UITableViewController{
var freshreleases = [Release_Date]()
let dateFormatter = DateFormatter()

override func viewDidLoad() {
super.viewDidLoad()

//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "Mic App Logo.png"), for: UIControlState.normal)

dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

let fetchRequest = Release_Date.fetchRequest() as NSFetchRequest<Release_Date>

let sortDescriptor1 = NSSortDescriptor(key: "album", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "artist", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
do {
freshreleases = try context.fetch(fetchRequest)
} catch let error {
print("Could not fetch because of error: (error).")
}

let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date < %@", startOfToday)
fetchRequest.predicate = predicate

tableView.reloadData()
}

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return freshreleases.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "FreshReleaseCellIdentifier", for: indexPath)

let freshrelease = freshreleases[indexPath.row]

cell.textLabel?.numberOfLines = 0

let artist = freshrelease.artist ?? ""
let album = freshrelease.album ?? ""
cell.textLabel?.text = artist + "'s nnew album '" + album + "'nreleases"

if let date = freshrelease.release_date as Date? {
cell.detailTextLabel?.text = dateFormatter.string(from: date)
} else {
cell.detailTextLabel?.text = ""
}

return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if freshreleases.count > indexPath.row {
let freshrelease = freshreleases[indexPath.row]

// Remove notification
if let identifier = freshrelease.release_dateId {
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [identifier])
}

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(freshrelease)
freshreleases.remove(at: indexPath.row)
do {
try context.save()
} catch let error {
print("Could not save (error)")
}
tableView.deleteRows(at: [indexPath], with: .fade)

}
}

@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

{
let modifyAction = UIContextualAction(style: .normal, title: "Update", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
success(true)
})
modifyAction.title = "Edit"
modifyAction.backgroundColor = .blue

return UISwipeActionsConfiguration(actions: [modifyAction])
}

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}









share|improve this question

























  • you can pass data in prepare for segue and also check MVVM

    – canister_exister
    Nov 14 '18 at 21:57











  • I can see where you are setting the data for the tableview but where/how do you refresh this information?

    – dniswhite
    Nov 14 '18 at 22:49











  • I do have this in the AppDelegate.Swift file: func applicationDidBecomeActive(_ application: UIApplication) {

    – sckring
    Nov 14 '18 at 23:11


















0















I'm working on an app which is date based. I'm trying to get information to pass from one TableViewController to another.



It's a notification based app that reminds the user that something comes out today. So on the date it comes out, I'd like it to come off the release list and go onto the released list (So if something comes out the Nov.8th, on that date it'll be moved to the released list).



I'm having trouble getting it to work. I used the below codes and the date comes and goes without anything happening, it still shows it on the release list.



I've tried several options and different variations of code but nothing seems to work.



I do have this code in the AppDelegate.Swift file so it refreshes the information:



 func applicationDidBecomeActive(_ application: UIApplication) { 


Below is the code I used on the release list:



let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date > %@", startOfToday)
fetchRequest.predicate = predicate


And here's the code on the released list:



let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date < %@", startOfToday)
fetchRequest.predicate = predicate


Here's the code for the FreshReleaseTableViewController:



import UIKit
import CoreData
import UserNotifications

class FreshReleaseTableViewController: UITableViewController{
var freshreleases = [Release_Date]()
let dateFormatter = DateFormatter()

override func viewDidLoad() {
super.viewDidLoad()

//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "Mic App Logo.png"), for: UIControlState.normal)

dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
}

@objc func editAction() {
let viewController = AddfreshreleaseViewController()
navigationController?.present(viewController, animated: true, completion: nil)
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

let fetchRequest = Release_Date.fetchRequest() as NSFetchRequest<Release_Date>

let sortDescriptor1 = NSSortDescriptor(key: "artist", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "album", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
do {
freshreleases = try context.fetch(fetchRequest)
} catch let error {
print("Could not fetch because of error: (error).")
}

let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date > %@", startOfToday)
fetchRequest.predicate = predicate

tableView.reloadData()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return freshreleases.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "FreshReleaseCellIdentifier", for: indexPath)

let freshrelease = freshreleases[indexPath.row]

cell.textLabel?.numberOfLines = 0

let artist = freshrelease.artist ?? ""
let album = freshrelease.album ?? ""
cell.textLabel?.text = artist + "'snnew album '" + album + "'nreleases"

if let date = freshrelease.release_date as Date? {
cell.detailTextLabel?.text = dateFormatter.string(from: date)
} else {
cell.detailTextLabel?.text = ""
}

return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}

// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if freshreleases.count > indexPath.row {
let freshrelease = freshreleases[indexPath.row]

// Remove notification
if let identifier = freshrelease.release_dateId {
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [identifier])
}

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(freshrelease)
freshreleases.remove(at: indexPath.row)
do {
try context.save()
} catch let error {
print("Could not save (error)")
}
tableView.deleteRows(at: [indexPath], with: .fade)
}
}

@available(iOS 11.0, *)

override func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

{
let modifyAction = UIContextualAction(style: .normal, title: "Edit", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
let MainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc : UIViewController = MainStoryboard.instantiateViewController(withIdentifier: "FreshReleaseEdit") as UIViewController
self.present(vc, animated: true, completion: nil)
success(true)

})
modifyAction.title = "Edit"
modifyAction.backgroundColor = .blue

return UISwipeActionsConfiguration(actions: [modifyAction])
}

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}


And here's the code for the ReleasedTableViewController:



import UIKit
import CoreData
import UserNotifications

class ReleasedTableViewController: UITableViewController{
var freshreleases = [Release_Date]()
let dateFormatter = DateFormatter()

override func viewDidLoad() {
super.viewDidLoad()

//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "Mic App Logo.png"), for: UIControlState.normal)

dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

let fetchRequest = Release_Date.fetchRequest() as NSFetchRequest<Release_Date>

let sortDescriptor1 = NSSortDescriptor(key: "album", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "artist", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
do {
freshreleases = try context.fetch(fetchRequest)
} catch let error {
print("Could not fetch because of error: (error).")
}

let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date < %@", startOfToday)
fetchRequest.predicate = predicate

tableView.reloadData()
}

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return freshreleases.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "FreshReleaseCellIdentifier", for: indexPath)

let freshrelease = freshreleases[indexPath.row]

cell.textLabel?.numberOfLines = 0

let artist = freshrelease.artist ?? ""
let album = freshrelease.album ?? ""
cell.textLabel?.text = artist + "'s nnew album '" + album + "'nreleases"

if let date = freshrelease.release_date as Date? {
cell.detailTextLabel?.text = dateFormatter.string(from: date)
} else {
cell.detailTextLabel?.text = ""
}

return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if freshreleases.count > indexPath.row {
let freshrelease = freshreleases[indexPath.row]

// Remove notification
if let identifier = freshrelease.release_dateId {
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [identifier])
}

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(freshrelease)
freshreleases.remove(at: indexPath.row)
do {
try context.save()
} catch let error {
print("Could not save (error)")
}
tableView.deleteRows(at: [indexPath], with: .fade)

}
}

@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

{
let modifyAction = UIContextualAction(style: .normal, title: "Update", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
success(true)
})
modifyAction.title = "Edit"
modifyAction.backgroundColor = .blue

return UISwipeActionsConfiguration(actions: [modifyAction])
}

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}









share|improve this question

























  • you can pass data in prepare for segue and also check MVVM

    – canister_exister
    Nov 14 '18 at 21:57











  • I can see where you are setting the data for the tableview but where/how do you refresh this information?

    – dniswhite
    Nov 14 '18 at 22:49











  • I do have this in the AppDelegate.Swift file: func applicationDidBecomeActive(_ application: UIApplication) {

    – sckring
    Nov 14 '18 at 23:11
















0












0








0








I'm working on an app which is date based. I'm trying to get information to pass from one TableViewController to another.



It's a notification based app that reminds the user that something comes out today. So on the date it comes out, I'd like it to come off the release list and go onto the released list (So if something comes out the Nov.8th, on that date it'll be moved to the released list).



I'm having trouble getting it to work. I used the below codes and the date comes and goes without anything happening, it still shows it on the release list.



I've tried several options and different variations of code but nothing seems to work.



I do have this code in the AppDelegate.Swift file so it refreshes the information:



 func applicationDidBecomeActive(_ application: UIApplication) { 


Below is the code I used on the release list:



let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date > %@", startOfToday)
fetchRequest.predicate = predicate


And here's the code on the released list:



let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date < %@", startOfToday)
fetchRequest.predicate = predicate


Here's the code for the FreshReleaseTableViewController:



import UIKit
import CoreData
import UserNotifications

class FreshReleaseTableViewController: UITableViewController{
var freshreleases = [Release_Date]()
let dateFormatter = DateFormatter()

override func viewDidLoad() {
super.viewDidLoad()

//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "Mic App Logo.png"), for: UIControlState.normal)

dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
}

@objc func editAction() {
let viewController = AddfreshreleaseViewController()
navigationController?.present(viewController, animated: true, completion: nil)
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

let fetchRequest = Release_Date.fetchRequest() as NSFetchRequest<Release_Date>

let sortDescriptor1 = NSSortDescriptor(key: "artist", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "album", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
do {
freshreleases = try context.fetch(fetchRequest)
} catch let error {
print("Could not fetch because of error: (error).")
}

let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date > %@", startOfToday)
fetchRequest.predicate = predicate

tableView.reloadData()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return freshreleases.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "FreshReleaseCellIdentifier", for: indexPath)

let freshrelease = freshreleases[indexPath.row]

cell.textLabel?.numberOfLines = 0

let artist = freshrelease.artist ?? ""
let album = freshrelease.album ?? ""
cell.textLabel?.text = artist + "'snnew album '" + album + "'nreleases"

if let date = freshrelease.release_date as Date? {
cell.detailTextLabel?.text = dateFormatter.string(from: date)
} else {
cell.detailTextLabel?.text = ""
}

return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}

// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if freshreleases.count > indexPath.row {
let freshrelease = freshreleases[indexPath.row]

// Remove notification
if let identifier = freshrelease.release_dateId {
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [identifier])
}

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(freshrelease)
freshreleases.remove(at: indexPath.row)
do {
try context.save()
} catch let error {
print("Could not save (error)")
}
tableView.deleteRows(at: [indexPath], with: .fade)
}
}

@available(iOS 11.0, *)

override func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

{
let modifyAction = UIContextualAction(style: .normal, title: "Edit", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
let MainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc : UIViewController = MainStoryboard.instantiateViewController(withIdentifier: "FreshReleaseEdit") as UIViewController
self.present(vc, animated: true, completion: nil)
success(true)

})
modifyAction.title = "Edit"
modifyAction.backgroundColor = .blue

return UISwipeActionsConfiguration(actions: [modifyAction])
}

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}


And here's the code for the ReleasedTableViewController:



import UIKit
import CoreData
import UserNotifications

class ReleasedTableViewController: UITableViewController{
var freshreleases = [Release_Date]()
let dateFormatter = DateFormatter()

override func viewDidLoad() {
super.viewDidLoad()

//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "Mic App Logo.png"), for: UIControlState.normal)

dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

let fetchRequest = Release_Date.fetchRequest() as NSFetchRequest<Release_Date>

let sortDescriptor1 = NSSortDescriptor(key: "album", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "artist", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
do {
freshreleases = try context.fetch(fetchRequest)
} catch let error {
print("Could not fetch because of error: (error).")
}

let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date < %@", startOfToday)
fetchRequest.predicate = predicate

tableView.reloadData()
}

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return freshreleases.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "FreshReleaseCellIdentifier", for: indexPath)

let freshrelease = freshreleases[indexPath.row]

cell.textLabel?.numberOfLines = 0

let artist = freshrelease.artist ?? ""
let album = freshrelease.album ?? ""
cell.textLabel?.text = artist + "'s nnew album '" + album + "'nreleases"

if let date = freshrelease.release_date as Date? {
cell.detailTextLabel?.text = dateFormatter.string(from: date)
} else {
cell.detailTextLabel?.text = ""
}

return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if freshreleases.count > indexPath.row {
let freshrelease = freshreleases[indexPath.row]

// Remove notification
if let identifier = freshrelease.release_dateId {
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [identifier])
}

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(freshrelease)
freshreleases.remove(at: indexPath.row)
do {
try context.save()
} catch let error {
print("Could not save (error)")
}
tableView.deleteRows(at: [indexPath], with: .fade)

}
}

@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

{
let modifyAction = UIContextualAction(style: .normal, title: "Update", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
success(true)
})
modifyAction.title = "Edit"
modifyAction.backgroundColor = .blue

return UISwipeActionsConfiguration(actions: [modifyAction])
}

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}









share|improve this question
















I'm working on an app which is date based. I'm trying to get information to pass from one TableViewController to another.



It's a notification based app that reminds the user that something comes out today. So on the date it comes out, I'd like it to come off the release list and go onto the released list (So if something comes out the Nov.8th, on that date it'll be moved to the released list).



I'm having trouble getting it to work. I used the below codes and the date comes and goes without anything happening, it still shows it on the release list.



I've tried several options and different variations of code but nothing seems to work.



I do have this code in the AppDelegate.Swift file so it refreshes the information:



 func applicationDidBecomeActive(_ application: UIApplication) { 


Below is the code I used on the release list:



let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date > %@", startOfToday)
fetchRequest.predicate = predicate


And here's the code on the released list:



let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date < %@", startOfToday)
fetchRequest.predicate = predicate


Here's the code for the FreshReleaseTableViewController:



import UIKit
import CoreData
import UserNotifications

class FreshReleaseTableViewController: UITableViewController{
var freshreleases = [Release_Date]()
let dateFormatter = DateFormatter()

override func viewDidLoad() {
super.viewDidLoad()

//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "Mic App Logo.png"), for: UIControlState.normal)

dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
}

@objc func editAction() {
let viewController = AddfreshreleaseViewController()
navigationController?.present(viewController, animated: true, completion: nil)
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

let fetchRequest = Release_Date.fetchRequest() as NSFetchRequest<Release_Date>

let sortDescriptor1 = NSSortDescriptor(key: "artist", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "album", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
do {
freshreleases = try context.fetch(fetchRequest)
} catch let error {
print("Could not fetch because of error: (error).")
}

let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date > %@", startOfToday)
fetchRequest.predicate = predicate

tableView.reloadData()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return freshreleases.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "FreshReleaseCellIdentifier", for: indexPath)

let freshrelease = freshreleases[indexPath.row]

cell.textLabel?.numberOfLines = 0

let artist = freshrelease.artist ?? ""
let album = freshrelease.album ?? ""
cell.textLabel?.text = artist + "'snnew album '" + album + "'nreleases"

if let date = freshrelease.release_date as Date? {
cell.detailTextLabel?.text = dateFormatter.string(from: date)
} else {
cell.detailTextLabel?.text = ""
}

return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}

// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if freshreleases.count > indexPath.row {
let freshrelease = freshreleases[indexPath.row]

// Remove notification
if let identifier = freshrelease.release_dateId {
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [identifier])
}

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(freshrelease)
freshreleases.remove(at: indexPath.row)
do {
try context.save()
} catch let error {
print("Could not save (error)")
}
tableView.deleteRows(at: [indexPath], with: .fade)
}
}

@available(iOS 11.0, *)

override func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

{
let modifyAction = UIContextualAction(style: .normal, title: "Edit", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
let MainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc : UIViewController = MainStoryboard.instantiateViewController(withIdentifier: "FreshReleaseEdit") as UIViewController
self.present(vc, animated: true, completion: nil)
success(true)

})
modifyAction.title = "Edit"
modifyAction.backgroundColor = .blue

return UISwipeActionsConfiguration(actions: [modifyAction])
}

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}


And here's the code for the ReleasedTableViewController:



import UIKit
import CoreData
import UserNotifications

class ReleasedTableViewController: UITableViewController{
var freshreleases = [Release_Date]()
let dateFormatter = DateFormatter()

override func viewDidLoad() {
super.viewDidLoad()

//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "Mic App Logo.png"), for: UIControlState.normal)

dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

let fetchRequest = Release_Date.fetchRequest() as NSFetchRequest<Release_Date>

let sortDescriptor1 = NSSortDescriptor(key: "album", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "artist", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
do {
freshreleases = try context.fetch(fetchRequest)
} catch let error {
print("Could not fetch because of error: (error).")
}

let startOfToday = Calendar.current.startOfDay(for: Date()) as NSDate
let predicate = NSPredicate(format: "release_date < %@", startOfToday)
fetchRequest.predicate = predicate

tableView.reloadData()
}

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return freshreleases.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "FreshReleaseCellIdentifier", for: indexPath)

let freshrelease = freshreleases[indexPath.row]

cell.textLabel?.numberOfLines = 0

let artist = freshrelease.artist ?? ""
let album = freshrelease.album ?? ""
cell.textLabel?.text = artist + "'s nnew album '" + album + "'nreleases"

if let date = freshrelease.release_date as Date? {
cell.detailTextLabel?.text = dateFormatter.string(from: date)
} else {
cell.detailTextLabel?.text = ""
}

return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if freshreleases.count > indexPath.row {
let freshrelease = freshreleases[indexPath.row]

// Remove notification
if let identifier = freshrelease.release_dateId {
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [identifier])
}

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(freshrelease)
freshreleases.remove(at: indexPath.row)
do {
try context.save()
} catch let error {
print("Could not save (error)")
}
tableView.deleteRows(at: [indexPath], with: .fade)

}
}

@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

{
let modifyAction = UIContextualAction(style: .normal, title: "Update", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
success(true)
})
modifyAction.title = "Edit"
modifyAction.backgroundColor = .blue

return UISwipeActionsConfiguration(actions: [modifyAction])
}

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}






swift uitableview core-data viewcontroller






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 16:44







sckring

















asked Nov 14 '18 at 21:46









sckringsckring

105




105













  • you can pass data in prepare for segue and also check MVVM

    – canister_exister
    Nov 14 '18 at 21:57











  • I can see where you are setting the data for the tableview but where/how do you refresh this information?

    – dniswhite
    Nov 14 '18 at 22:49











  • I do have this in the AppDelegate.Swift file: func applicationDidBecomeActive(_ application: UIApplication) {

    – sckring
    Nov 14 '18 at 23:11





















  • you can pass data in prepare for segue and also check MVVM

    – canister_exister
    Nov 14 '18 at 21:57











  • I can see where you are setting the data for the tableview but where/how do you refresh this information?

    – dniswhite
    Nov 14 '18 at 22:49











  • I do have this in the AppDelegate.Swift file: func applicationDidBecomeActive(_ application: UIApplication) {

    – sckring
    Nov 14 '18 at 23:11



















you can pass data in prepare for segue and also check MVVM

– canister_exister
Nov 14 '18 at 21:57





you can pass data in prepare for segue and also check MVVM

– canister_exister
Nov 14 '18 at 21:57













I can see where you are setting the data for the tableview but where/how do you refresh this information?

– dniswhite
Nov 14 '18 at 22:49





I can see where you are setting the data for the tableview but where/how do you refresh this information?

– dniswhite
Nov 14 '18 at 22:49













I do have this in the AppDelegate.Swift file: func applicationDidBecomeActive(_ application: UIApplication) {

– sckring
Nov 14 '18 at 23:11







I do have this in the AppDelegate.Swift file: func applicationDidBecomeActive(_ application: UIApplication) {

– sckring
Nov 14 '18 at 23:11














0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53309200%2fswift-getting-tableviewcontrollers-to-talk-to-one-another%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53309200%2fswift-getting-tableviewcontrollers-to-talk-to-one-another%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Florida Star v. B. J. F.

Danny Elfman

Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues