简体   繁体   中英

Fire local push notification on selected date and time in swift

I need to fire push notification on below date and time at 9:00 AM :

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

Please Help!

Here we use Trigger notification: Calendar: Trigger at a specific date and time. The trigger is created using a date components object which makes it easier for certain repeating intervals. To convert a Date to its date components use the current calendar. For example:

`// 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];`

To create the trigger from the date components:

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

To create a trigger that repeats at a certain interval use the correct set of date components. For example, to have the notification repeat daily at the same time we need just the hour, minutes and seconds:

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

To have it repeat weekly at the same time we also need the weekday:

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

This is an interesting change from the older notification framework which had a fire date and repeat interval. The date components are more flexible but there is no easy way to fully replicate the fireDate property of the older framework. For example, if I want a daily trigger that starts in 1 week.

please gothrough

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM