我有一个待办事项应用程序。在核心数据中,我存储了一些带有 id、taskName、taskDate 的任务。现在我想指示我的应用程序在每周一和周二的 taskDate(例如上午 9:00)执行本地 UserNotification。我尝试用 UNTimeIntervalNotificationTrigger 来做,但这不起作用。
谁能告诉我,我怎样才能在星期一和星期二添加一个特定的时间来触发通知?
这是代码:
@IBAction func notifyButtonTapped(_ sender: Any) {
scheduleNotification(inSeconds: 20, title: "title", subtitle: "subtitle", body: "", completion: { success in
if success {
print("Successfully scheduled notification")
} else {
print("Erro scheduling notifiation")
}
})
}
func scheduleNotification(inSeconds: TimeInterval, title: String, subtitle: String, body:String, completion: @escaping (_ Success: Bool) -> ()) {
let titleIn = title
let subtitleIn = subtitle
let bodyIn = body
// Add an attachment
let myImage = "IconNotify"
guard let imageUrl = Bundle.main.url(forResource: myImage, withExtension: "png") else {
completion(false)
return
}
var attachement: UNNotificationAttachment
attachement = try! UNNotificationAttachment(identifier: "myNotification", url: imageUrl, options: .none)
let nofif = UNMutableNotificationContent()
//ONLY FOR EXTENSION
nofif.categoryIdentifier = "myNotificationCategory"
nofif.title = titleIn
nofif.subtitle = subtitleIn
nofif.body = "TaskBody"
nofif.badge = 1
nofif.attachments = [attachement]
let nofifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: inSeconds, repeats: false)
let request = UNNotificationRequest(identifier: "myNotification", content: nofif, trigger: nofifTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: {error in
if error != nil {
print(error)
completion(false)
} else {
completion(true)
}
})
}
在 AppDelegate 我这样做:
private func configureUserNotifications() {
let okAction = UNNotificationAction(identifier: "okBump", title: "Ok", options: [])
let dismissAction = UNNotificationAction(identifier: "dismiss", title: "Remind me later", options: [])
let category = UNNotificationCategory(identifier: "myNotificationCategory", actions: [okAction, dismissAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Response received for \(response.actionIdentifier)")
completionHandler()
} }
非常感谢。