Swift 每 5 天重复一次 LocalNotification
Posted
技术标签:
【中文标题】Swift 每 5 天重复一次 LocalNotification【英文标题】:Swift Repeat LocalNotification every 5 days 【发布时间】:2018-04-02 08:00:41 【问题描述】:如何在每 5 天上午 10:00 重复一次 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)
【问题讨论】:
而不是计算futureTime
,也许你应该使用DateComponents#day
请检查一下。 ***.com/questions/4363847/…
【参考方案1】:
您可以使用UNCalendarNotificationTrigger
获取本地通知,该通知在任何特定日期或星期的任何特定时间重复。
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Hello!"
//notificationContent.subtitle = "Something"
notificationContent.body = "Hello_message_body"
notificationContent.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: notificationContent, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
谢谢。
【讨论】:
嗨!,我正在使用相同的功能,但没有收到通知,甚至没有重复通知。以上是关于Swift 每 5 天重复一次 LocalNotification的主要内容,如果未能解决你的问题,请参考以下文章