簡體   English   中英

迅速在選定的日期和時間觸發本地推送通知

[英]Fire local push notification on selected date and time in swift

我需要在以下日期和時間在上午 9:00 發出推送通知:

January: 13rd, 18th, 20th, 23rd 

請幫忙!

這里我們使用觸發通知: 日歷:在特定日期和時間觸發。 觸發器是使用日期組件對象創建的,這使得某些重復間隔更容易。 要將日期轉換為其日期組件,請使用當前日歷。 例如:

`// Swift
let date = Date(timeIntervalSinceNow: 3600)
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,],from: date)
//Objective-C
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3600];
NSDateComponents *triggerDate = [[NSCalendar currentCalendar]   
          components:NSCalendarUnitYear +
          NSCalendarUnitMonth + NSCalendarUnitDay +
          NSCalendarUnitHour + NSCalendarUnitMinute +
          NSCalendarUnitSecond fromDate:date];`

要從日期組件創建觸發器:

// Swift
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
// Objective-C
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:NO];

要創建以特定時間間隔重復的觸發器,請使用正確的日期組件集。 例如,要讓通知每天在同一時間重復,我們只需要小時、分鍾和秒:

let triggerDaily = Calendar.current.dateComponents([hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)

為了讓它每周在同一時間重復,我們還需要工作日:

let triggerWeekly = Calendar.current.dateComponents([.weekday,hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)

這是與具有觸發日期和重復間隔的舊通知框架的有趣變化。 日期組件更靈活,但沒有簡單的方法來完全復制舊框架的 fireDate 屬性。 例如,如果我想要一個在 1 周后開始的每日觸發器。

請通過

UNCalendarNotificationTrigger https://developer.apple.com/documentation/usernotifications/uncalendarnotificationtrigger

訪問https://useyourloaf.com/blog/local-notifications-with-ios-10/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM