如何每天重复一个 UNUserNotification?

How to repeat a UNUserNotification every day?

我试图让用户安排每天在特定时间打开应用程序的通知。到目前为止,我已经能够通过计算从现在到用户选择之间的时间来安排第一个通知,并在 X 秒内安排通知。但是,有没有一种方法可以将通知设置为每天重复?如果您感到困惑,这是我的部分代码:

let newTime: Double = Double(totalDifference)
let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: false)
let request = UNNotificationRequest(identifier: "openApp", content: notif, trigger: notifTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
    if error != nil {
        print(error!)
        completion(false)
    } else {
        completion(true)
    }
})

非常感谢任何帮助

对于您的情况,更改此行:

let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: false)

let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: true)

来自文档:

UNCalendarNotificationTrigger:

Triggers a notification at the specified date and time. You use a UNCalendarNotificationTrigger object to specify the temporal information for the trigger condition of a notification. Calendar triggers can fire once or they can fire multiple times.

NSDateComponents* date = [[NSDateComponents alloc] init];
date.hour = 8;
date.minute = 30; 
UNCalendarNotificationTrigger* trigger = [UNCalendarNotificationTrigger
                     triggerWithDateMatchingComponents:date repeats:YES];

Swift:

var date = DateComponents()
date.hour = 8
date.minute = 30 
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)

对于 SWIFT3

    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents(in: .current, from: date)
    let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)