To Do アプリがあります。Core Data には、id、taskName、taskDate を使用していくつかのタスクを保存します。ここで、毎週月曜日と火曜日の taskDate (例: 午前 09: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()
} }
本当にありがとう。