Fire a Notification at a Specific Day and Time Every Week

Fire a notification at a specific day and time every week

You missed the NSWeekCalendarUnit in the NSDateComponents init function. Add the NSWeekCalendarUnit to it and set the repeatInterval to NSWeekCalendarUnit, then output is

next fire date = Sunday, November 24, 2013 at 8:00:00 PM  

The code is here:

  NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: now];
[componentsForFireDate setWeekday: 1] ; //for fixing Sunday
[componentsForFireDate setHour: 20] ; //for fixing 8PM hour
[componentsForFireDate setMinute:0] ;
[componentsForFireDate setSecond:0] ;

//...
notification.repeatInterval = NSWeekCalendarUnit;
//...

Repeating local notifications for specific days of week (Swift 3 IOS 10)

You can use below function to get Date from selected picker value:

    //Create Date from picker selected value.
func createDate(weekday: Int, hour: Int, minute: Int, year: Int)->Date{

var components = DateComponents()
components.hour = hour
components.minute = minute
components.year = year
components.weekday = weekday // sunday = 1 ... saturday = 7
components.weekdayOrdinal = 10
components.timeZone = .current

let calendar = Calendar(identifier: .gregorian)
return calendar.date(from: components)!
}

//Schedule Notification with weekly bases.
func scheduleNotification(at date: Date, body: String, titles:String) {

let triggerWeekly = Calendar.current.dateComponents([.weekday,.hour,.minute,.second,], from: date)

let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)

let content = UNMutableNotificationContent()
content.title = titles
content.body = body
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "todoList"

let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)

UNUserNotificationCenter.current().delegate = self
//UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}

After getting a value from picker pass picker hour, minute and year with selected week day as (Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4, thursday = 5, Friday = 6, Saturday = 7) to function func createDate(weekday: Int, hour: Int, minute: Int, year: Int) to get notification fire date on weekly bases, and after getting date call function func scheduleNotification(at date: Date, body: String, titles:String) for schedule a notification.

Local Notification every specific day of week

You can use NSDateComponents to create the exact date for your local notification. Here is the example, how do we create local notification with exact fire date:

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:now];//get the required calendar units

if (components.weekday>2) {
components.weekOfYear+=1;//if already passed monday, make it next monday
}
components.weekday = 2;//Monday
components.hour = 11;
NSDate *fireDate = [calendar dateFromComponents:components];

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = fireDate;
localNotification.alertBody = @"alert message";
localNotification.applicationIconBadgeNumber = 1;
localNotification.repeatInterval = NSCalendarUnitWeekOfYear;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

In this piece of code, I set the fire date to every Monday 11 a.m, and set it repeat weekly using repeatInterval of local notification. Code maybe wrong, need to test, but I guess this gives you the basic idea, also I don't code in swift, so it's objective c. Hope this helps!

I need to set a notification on a specific day every week.. but I don`t care the day of the month

Get the next Sunday or Monday date (SO answer), use calendar method dateBySettingHour to set the desired time to that date and use it as the firedate using the weekofyear repeat interval.

Scheduling weekly repeatable local notification with fire date from date picker in Swift 3

As McNight mentionned, you can use UNCalendarNotificationTrigger like so:

let interval = 60 * 60 * 24 * 7 - 300 // One week minus 5 minutes.
let alarmTime = Calendar.current.date(byAdding: .second, value: interval, to: Date())!
let components = Calendar.current.dateComponents([.weekday, .hour, .minute], from: alarmTime)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)

(I haven't tested this code, but this should get you on the right path).

More information here.

Edit: Fixed time interval calculation suggested by SwiftyCruz.

Edit 2: Updated to use a Calendar to perform the time shift as suggested by RickiG.

Schedule Local Notifications at Specific times in the day

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let settings = UIUserNotificationSettings(forTypes: .Badge, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)

let localNotification1 = UILocalNotification()
localNotification1.alertBody = "Your alert message 111"
localNotification1.timeZone = NSTimeZone.defaultTimeZone()
localNotification1.fireDate = self.getEightAMDate()
UIApplication.sharedApplication().scheduleLocalNotification(localNotification1)

let localNotification2 = UILocalNotification()
localNotification2.alertBody = "Your alert message22"
localNotification2.timeZone = NSTimeZone.defaultTimeZone()
localNotification2.fireDate = self.getSevenPMDate()
UIApplication.sharedApplication().scheduleLocalNotification(localNotification2)
return true
}

func getEightAMDate() -> NSDate? {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()

let date10h = calendar.dateBySettingHour(8, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)!
return date10h
}

func getSevenPMDate() -> NSDate? {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()

let date19h = calendar.dateBySettingHour(19, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)!
return date19h
}

iOS local notification base on day, time frame and number of times?

If you want to schedule multiple notifications, you need to create multiple notification triggers and register them.

something like:

// Simple extension if you have to create multiple of the same object
extension DateComponents {
static func triggerFor(hour: Int, minute: Int) -> DateComponents {
var component = DateComponents()
component.calendar = Calendar.current
component.hour = hour
component.minute = minute
component.weekday = 1
return component
}
}

// Add each trigger into an array with the correct date component
let triggers = [
UNCalendarNotificationTrigger(dateMatching: DateComponents.triggerFor(hour: 1, minute: 0), repeats: true),
UNCalendarNotificationTrigger(dateMatching: DateComponents.triggerFor(hour: 2, minute: 0), repeats: true),
UNCalendarNotificationTrigger(dateMatching: DateComponents.triggerFor(hour: 3, minute: 0), repeats: true),
UNCalendarNotificationTrigger(dateMatching: DateComponents.triggerFor(hour: 4, minute: 0), repeats: true),
UNCalendarNotificationTrigger(dateMatching: DateComponents.triggerFor(hour: 5, minute: 0), repeats: true)
]

// Iterate through the array and register the notification with the system
for trigger in triggers {
// Create the content of the notification
let content = UNMutableNotificationContent()
content.title = "My Notification Title"
content.body = "Body of Notification"

// Create the request
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString,
content: content, trigger: trigger)

// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
if error != nil {
// Handle any errors.
}
}
}


Related Topics



Leave a reply



Submit