[英]Xamarin Forms - Daily event based on time for schedulled local daily notification
[英]UNNotificationRequest to send local notification daily at a specific time
由於 UILocalNotification 在 iOS10 中已棄用,我無法理解如何將以下代碼更新到 UNNotificationRequest 框架。 我基本上讓用戶在他們選擇的時間安排每日通知。 例如,如果他們想每天上午 11:00 收到通知。 以下代碼適用於 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)
您可以使用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")
}
})
您無法安排每天重復的通知。 該通知只會發生一次,然后您必須再次安排它,這意味着您必須再次打開該應用程序。
iOS 13中引入了BGTask API,可以用來執行一些后台任務,但不是這個,你不能把任務安排在特定的時間。這個API最后只在app在后台時有效,在app處於后台時無效被殺。 您只能設置一些時間間隔,系統將用作指導點來確定何時執行您的應用程序代碼。 但根據我的經驗,這是非常不可靠的。
實現這一點的唯一方法是實現遠程推送通知。 即使應用程序被終止,推送通知也能正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.