事件日期过后,获取信息在TableViewController之间传递-Swift

时间:2018-11-01 20:30:46

标签: swift uitableview datepicker viewcontroller

我目前正在开发一个应用,该应用会在发布新音乐时通知用户。用户输入艺术家,专辑,发行日期(他们使用日期选择器选择日期)并将其保存到列表中。当天,他们收到此专辑今天发布的通知。

日期过后,我希望它离开FreshListTableViewController并进入ReleasedTableViewController。

感谢您的帮助。

以下是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


    //let button1 = UIButton()
    //button1.addTarget(self, action: #selector(editAction), for: .touchUpInside)

    //self.tableView.backgroundColor = UIColor.white

}


@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).")
    }
    tableView.reloadData()
}


// MARK: - Table view data source

override func numberOfSections(in 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 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 to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    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 to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

}
*/

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

}

下面是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

    //self.tableView.backgroundColor = UIColor.white

}

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).")
    }
    tableView.reloadData()
}


// MARK: - Table view data source

override func numberOfSections(in 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 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 to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    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:  "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 to support rearranging the table view.
 override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

 }
 */

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

}

1 个答案:

答案 0 :(得分:0)

对不起,您需要进一步澄清问题。

根据您所说的内容:

  

日期过后,我希望它离开   FreshListTableViewController并转到   ReleasedTableViewController。

您是说它当前没有更新吗?当我查看代码时,看不到它所执行的部分。意思是说,我发现您正在使用appDelegate.persistentContainer.viewContext,但没有看到更新来检查已发行的专辑。

如果我理解的是正确的,则可能要在CoreData中包含release_date属性,并在CoreData中按当前日期进行过滤。 如果您使用的是.xcdatamodeld文件,请在其中存储Date的release_date属性中添加。

在您的FreshReleaseTableViewController中,

// ==== Filter by date
    let startOfToday = Calendar.current.startOfDay(Date()) as! NSDate
    var predicate = NSPredicate(format: "(your_date_attribute_name) > %@)", startOfToday)
    fetchRequest.predicate = predicate
// ======

对于您的ReleaseTableViewController来说反之亦然,

// ==== Filter by date
let startOfToday = Calendar.current.startOfDay(Date()) as! NSDate
var predicate = NSPredicate(format: "(your_date_attribute_name) < %@)", startOfToday)
fetchRequest.predicate = predicate
// ======