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 + "'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 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
    }
}
sckring
  • 31
  • 5

0 Answers0