我目前有一个函数,可以将 Realm 对象写入数据库并写入通知。当对象被写入时,它被添加到 uicollectionview 中并显示。下面的函数添加对象并基于 UIDatePicker 设置通知。该代码未显示,因为它有很多与问题无关:
func createTaskWithDate() {
let task = Task()
task.name = textField.text!
//notification code under here
try! realm.write {
realm.add(task)
updateData()
}
我还有另一个函数可以响应通知集上的操作。当用户点击通知时,他们可以选择“标记为完成”。当用户点击“标记为完成”时,我尝试从“createTaskWithDate()”方法检索对象并将其从 Collection View 中删除,但我不确定如何从该方法检索该对象:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let identifier = response.actionIdentifier
let request = response.notification.request
if identifier == "complete" {
try! realm.write {
//realm.delete(task object from createTaskWithDate())
updateData()
}
}
completionHandler()
}
我怎样才能做到这一点?
最佳答案
设置通知时,您应该在通知请求中存储通知所涉及的对象的名称/主键。您可以将任何信息存储在 UNMutableNotificationContent.userInfo
中,并通过
userNotificationCenter(_:didReceive:withCompletionHandler:)
中访问它
让 userInfo = response.notification.content.userInfo
。
然后您可以使用存储在 userInfo
中的主键从 Realm
检索对象。
关于ios - 如何从不同的函数检索 Realm 对象? swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45468600/