我有这个帮助方法来创建一个本地通知,该通知每天都会在特定的时间调用:
func create(_ type: NotificationType, time: Date, title: String, body: String, repeated: Bool = false) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default()
let triggerDate = Calendar.current.dateComponents([.hour, .minute], from: time)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
let identifier = type.rawValue
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
center.add(request) { error in
if let error = error {
fatalError("Unable to add request to Notification Center - \(error)")
}
}
}
然后我每次启动应用程序时都会调用它:
notifications.create(.tomorrow, time: Date.tomorrowsTime,
title: "" ,
body: "",
repeated: true)
如果我每次启动应用程序时安排它,是否安全?或者我应该确保只在应用程序第一次运行时调用一次?