gpt4 book ai didi

ios - 一旦日期过去,将数据从一个 TableViewController 传输到另一个 TableViewController

转载 作者:行者123 更新时间:2023-11-30 11:02:02 26 4
gpt4 key购买 nike

我正在开发一个基于日期的应用程序。我正在尝试获取从一个 TableViewController 传递到另一个 TableViewController 的信息。

这是一个基于通知的应用程序,可以提醒用户今天有事情发生。因此,在它发布的那一天,我希望它从发布列表中消失并进入发布列表(因此,如果有东西在 11 月 8 日发布,那么在那一天它将被移动到发布列表中)。

我无法让它正常工作。我使用了下面的代码,日期来了又去,没有发生任何事情,它仍然显示在发布列表上。

下面是我在发布列表中使用的代码:

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

这是已发布列表中的代码:

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

这是 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
}
}

这是 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
}
}

最佳答案

对此有许多潜在的解决方案。

我建议的最简单的方法是你的 View Controller 监听 UIApplicationDidBecomeActiveNotification 。当此通知触发时,您可以运行重建您的提取请求并再次执行它。然后,这将为您提供列表的最新版本。

另一种选择是稍微更改您的数据模型,以在数据模型中包含 isReleased 标志。现在,在您的应用程序委托(delegate)中,您可以实现 applicationDidBecomeActive 。调用此方法时,您可以触发数据库更新以刷新 isReleased 标志。在 View Controller 中,您可以使用 NSFetchedResultController并将查询的谓词更改为:

 // Unreleased movies
fetchRequest.predicate = NSPredicate(format: "isReleased = NO")

// Released movies
fetchRequest.predicate = NSPredicate(format: "isReleased = YES")

获取的结果 Controller 具有委托(delegate)协议(protocol),可让您监听底层数据存储的更改,从而使您有机会更新 UI。

关于ios - 一旦日期过去,将数据从一个 TableViewController 传输到另一个 TableViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53240343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com