如何每天重复UNUserNotification?

Spe*_*nak 2 ios swift ios10 unusernotificationcenter

我正在尝试允许用户安排通知,以便在每天的特定时间打开应用.到目前为止,我已经能够通过计算从现在到用户选择的时间以及在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)
    }
})
Run Code Online (Sandbox Code Playgroud)

任何帮助深表感谢

Tej*_*uri 6

在您的情况下,更改此行:

let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: false)
Run Code Online (Sandbox Code Playgroud)

let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: true)
Run Code Online (Sandbox Code Playgroud)

从文档:

UNCalendarNotificationTrigger:

在指定的日期和时间触发通知.您使用UNCalendarNotificationTrigger对象指定通知的触发条件的时间信息.日历触发器可以触发一次,也可以多次触发.

NSDateComponents* date = [[NSDateComponents alloc] init];
date.hour = 8;
date.minute = 30; 
UNCalendarNotificationTrigger* trigger = [UNCalendarNotificationTrigger
                     triggerWithDateMatchingComponents:date repeats:YES];
Run Code Online (Sandbox Code Playgroud)

迅速:

var date = DateComponents()
date.hour = 8
date.minute = 30 
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
Run Code Online (Sandbox Code Playgroud)