问题
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