每5天快速重复一次LocalNotification

时间:2018-04-02 08:00:42

标签: ios swift localnotification unusernotificationcenter

如何在上午10:00每隔5天重复一次LocalNotification

我试试这个,但它不起作用

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 个答案:

答案 0 :(得分:2)

您可以使用UNCalendarNotificationTrigger获取在任何特定时间的任何定义天或周重复的本地通知。

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 a.m.
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)

谢谢。

相关问题