由于UILocalNotification在iOS10中已弃用,因此我很难理解如何将以下代码更新为UNNotificationRequest框架。我基本上是让用户在他们选择的时间安排每日通知。例如,如果他们想每天11:00 AM收到通知。以下代码适用于iOS10以下的iOS版本,但由于不推荐使用UILocalNotification,因此不再有效。任何帮助将不胜感激。
let notification = UILocalNotification()
notification.fireDate = fixedNotificationDate(datePicker.date)
notification.alertBody = "Your daily alert is ready for you!"
notification.timeZone = TimeZone.current
notification.repeatInterval = NSCalendar.Unit.day
notification.applicationIconBadgeNumber = 1
UIApplication.shared.scheduleLocalNotification(notification)
答案 0 :(得分:2)
您可以使用UNCalendarNotificationTrigger
创建使用UNUserNotificationCenter
反复触发的通知。你可以做这样的事情。诀窍是仅在触发日期中包含时间部分。
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Attention!"
content.body = "Your daily alert is ready for you!"
content.sound = UNNotificationSound.default
let identifier = "com.yourdomain.notificationIdentifier"
var triggerDate = DateComponents()
triggerDate.hour = 18
triggerDate.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
print("Error : \(error.localizedDescription)")
} else {
// Something went right
print("Success")
}
})
答案 1 :(得分:0)
您不能安排每天重复的通知。该通知只会发生一次,然后您将不得不再次安排它,这意味着您将不得不再次打开该应用程序。
iOS 13中引入了BGTask API,可用于执行一些后台任务,但不能执行此操作,您不能在特定时间安排任务。该API仅在以下情况下有效:应用程序在后台,而不是在被杀死时。您只能设置一些时间间隔,系统将以此为指导来确定何时执行应用程序代码。但是根据我的经验,这是非常不可靠的。
实现此目的的唯一方法是实现远程推送通知。即使应用被终止,推送通知也可以工作。