【发布时间】:2018-09-08 18:03:27
【问题描述】:
我正在尝试根据用户为我正在处理的应用程序指定的日期和时间创建通知。我能够保存用户的日期并检索。我现在希望在用户指定的日期到达时弹出通知,就像提醒一样。我可以使用硬编码值创建通知,但现在从 Real 数据库中检索以传递到触发器值是我无法做到的。我的代码在下面指定
func notifcation() -> Void {
let calendar = Calendar.current
let components = DateComponents(year: 2018, month: 09, day: 08, hour: 18, minute: 55) // Set the date here when you want Notification
let date = calendar.date(from: components)
let comp2 = calendar.dateComponents([.year,.month,.day,.hour,.minute], from: date!)
let trigger = UNCalendarNotificationTrigger(dateMatching: comp2, repeats: true)
let content = UNMutableNotificationContent()
content.title = "Don't forget"
content.body = "Buy some milk"
content.sound = UNNotificationSound.default()
let identifier = "UYLLocalNotification"
let request = UNNotificationRequest(identifier: identifier,
content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
print(error as Any)
}
})
}
然后我在 viewDidLoad 中调用 notification()
型号
class ListModel: Object {
@objc dynamic var createdDate: Date?
@objc dynamic var remiderDate: Date?
}
基于 Sh 的回答 我的功能
func getDataFromDB() -> Results<ListModel>? {
let todoListArray: Results<ListModel> = database.objects(ListModel.self)
return todoListArray
}
我的 viewdidLoad 现在是
TodoListFunctions.instance.getDataFromDB()?.forEach({ (list) in
notifcation(list.remiderDate)
})
在我的 AppDelegate 中获取权限
let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .sound]
center.requestAuthorization(options: options) {
(granted, error) in
if !granted {
print("Something went wrong")
}
}
可根据要求提供更多代码
【问题讨论】: