我正在尝试根据用户为正在处理的应用程序指定的日期和时间创建通知。我可以保存用户的日期并进行检索。现在,我想在用户指定的日期到来时像提醒一样弹出通知。我可以使用硬编码的值创建一个通知,但是现在无法从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")
}
}
更多代码将应要求提供
答案 0 :(得分:0)
您可以尝试
let allList = self.database.objects(ListModel.self)
allList.forEach{ notifcation($0.remiderDate) }
//
func notifcation(_ reminder:Date?) -> Void {
guard let date = reminder else { return }
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 = "\(date)" // identider should be different for each one
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)
}
})
}
//
在AppDelegte中设置委托
UNUserNotificationCenter.current().delegate = self
并注意
中的打印内容func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("notification received")
}