Swift Repeat LocalNotification every 5 days

 ̄綄美尐妖づ 提交于 2020-03-23 04:35:24

问题


How to repeat LocalNotification every 5 days at 10:00 AM

I try this, but it's not working

let content = UNMutableNotificationContent()
content.title = "Hello!"
content.body = "Hello_message_body"
content.sound = UNNotificationSound.default()

let futureTime = Date().addingTimeInterval(5 * 24 * 60 * 60)
var calendar = NSCalendar.current
calendar.timeZone = NSTimeZone.system
var components = calendar.dateComponents([.hour, .minute, .second], from: futureTime)
components.hour = 10
components.minute = 0
components.second = 0

let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: "FiveDays", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)

回答1:


You can use UNCalendarNotificationTrigger to get Local Notification that repeats for any define days or week at any certain time.

let notification = UNMutableNotificationContent()
notification.title = "Hello!"
//notification.subtitle = "Something"
notification.body = "Hello_message_body"
content.sound = UNNotificationSound.default

// Add notification for Friday (after 5 days) at 10:00 AM
var dateComponents = DateComponents()
dateComponents.weekday = 5
dateComponents.hour = 10
dateComponents.minute = 0

let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

Thank you.



来源:https://stackoverflow.com/questions/49607506/swift-repeat-localnotification-every-5-days

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!