Repetitive Push Alert Swift - ios

Hi, I am trying to make a push alert in swift that goes off every morning at 7 AM local time (not GMT).
Here's my code:
func scheduleLocalNotification() {
var localNotification = UILocalNotification()
localNotification.timeZone = timeZone
//localNotification.fireDate = Here is where I need help.
localNotification.alertBody = "FooBar"
localNotification.alertAction = "BarFoo"
}
I cannot seem to figure out how to achieve code that sends a push notification every morning at 7 AM local time, rather than just once at 7:00 AM. How do I do this? Is there a NSDate object that can do this? Different code all together?
Thanks!

Use the repeatInterval field to set up a repeat and use NSCalendar to calculate the next 7 AM
let calendar = NSCalendar.currentCalendar()
// Calculate the next 7 AM
var date = calendar.dateBySettingHour(7, minute: 0, second: 0, ofDate: NSDate(), options:nil)
if date?.timeIntervalSinceNow < 0 {
date = calendar.dateByAddingUnit(.CalendarUnitDay, value: 1, toDate: date!, options: nil)
}
localNotification.fireDate = date
// Set up a daily repeat
localNotification.repeatInterval = .CalendarUnitDay
localNotification.repeatCalendar = calendar

Related

Local notification not firing if repeat is set to daily

I've been facing a very strange error when trying to schedule a notification. The user provides the hour and minute when they want to have their local notification, and they can choose if they want it to be scheduled daily weekly or monthly.
However, I have run into a very weird problem. This is my code:
func enableLocalNotifications() {
notificationsSwitch.isOn = true
notificationsOn = true
//first cancel all current local notifications
UIApplication.shared.cancelAllLocalNotifications()
//create new one according to input
let calendar = Calendar(identifier: .gregorian)
var fireComponents=calendar.dateComponents([.day, .month, .year], from:NSDate() as Date)
fireComponents.hour = notificationHour
fireComponents.minute = notificationMinute
fireComponents.second = 00
fireComponents.calendar = calendar
let notification = UILocalNotification()
notification.timeZone = NSTimeZone.local
notification.alertBody = notificationDescription
notification.alertTitle = "Reminder"
notification.fireDate = fireComponents.date
notification.soundName = UILocalNotificationDefaultSoundName
switch notificationRepeat {
case "Daily":
notification.repeatInterval = NSCalendar.Unit.minute
case "Weekly":
notification.repeatInterval = NSCalendar.Unit.weekOfYear
case "Monthly":
notification.repeatInterval = NSCalendar.Unit.month
default:
break
}
UserDefaults.standard.setValue(notificationRepeat, forKey: "notificationRepeat")
UserDefaults.standard.setValue(notificationDescription, forKey: "notificationDescription")
UserDefaults.standard.setValue(notificationHour, forKey: "notificationHour")
UserDefaults.standard.setValue(notificationMinute, forKey: "notificationMinute")
UserDefaults.standard.setValue(true, forKey: "notificationSet")
}
}
The funny thing is, if I for example want to create a "daily" notification at 12:00, and at the moment it is 11:59, it just won't fire the notification at 12:00, actually it fires nothing at all. However, I have noticed, if I change the repeatInterval to NSCalendar.Unit.minute, then suddenly, if I schedule a notification for 12:00, and it's 11:59, I really receive it at 12:00.
Is there any fix for my bug?
Double check whether the date you are setting to notification.fireDate is correct or not. Sometimes due to not setting proper timezones the date and time changes and it won't come at your expecting time.

Local notifications firing immediately instead of when they are scheduled

I've been trying to schedule local notifications by weekday, but they seem to be firing immediately instead of when I schedule them. This is my code in AppDelegate in didFinishLaunchingWithOptions:
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil))
var notification = UILocalNotification()
var components = NSDateComponents()
var calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
components.weekday = 5
components.hour = 9
components.minute = 24
notification.alertBody = "Notification test"
notification.fireDate = calendar?.dateFromComponents(components)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Any clues on why it might not be working?
As others have mentioned, make sure to specify the year and month properties of the components object.
components.year = 2016
components.month = 6
Part of the current fire date of your code is the following:
0001-01-01
Which means the notification will be fired at year "1" in January, not in 2016.
You need to use notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
Try to set a year/month because it is created from 01/01/1970, so the date is in the past => immediate trigger

Schedule local notification at specific day and hour

How can I schedule a local notification that fire every Wednesday and Saturday at noon local device time?
let localNoonSatNotification:UILocalNotification = UILocalNotification()
localNoonSatNotification.userInfo = ["uid":"noonBreak"]
localNoonSatNotification.alertAction = "Noon Break"
localNoonSatNotification.alertBody = "Time for a break! Come and play few levels"
localNoonSatNotification.fireDate = // get next Wednesday/Saturday 12:00 PM
localNoonSatNotification.soundName = UILocalNotificationDefaultSoundName
localNoonSatNotification.applicationIconBadgeNumber = 1
UIApplication.sharedApplication().scheduleLocalNotification(localNoonSatNotification)
If someone still needs help with this question UNCalendarNotificationTrigger
// Configure the recurring date.
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.weekday = 3 // Tuesday
dateComponents.hour = 14 // 14:00 hours
// Create the trigger as a repeating event.
let trigger = UNCalendarNotificationTrigger(
dateMatching: dateComponents, repeats: true)
You can set repeat interval,
notification.repeatInterval = NSCalendarUnit.CalendarUnitWeekday
Hope this will help :)

Set notification at specific time Swift

I want to set notification at the time (hour, minute) that I set. But It show error:
func notification(story: Story) {
let dateComponents = NSDateComponents.init()
dateComponents.weekday = 5
dateComponents.hour = story.remindeAtHour
dateComponents.minute = story.remindeAtMinute
let notification = UILocalNotification()
notification.alertAction = "Title"
notification.alertBody = "It's time to take a photo"
notification.repeatInterval = NSCalendarUnit.WeekOfYear
notification.fireDate = dateComponents.calendar
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
As Paul w points out in his comment, the error message is telling you what's wrong.
You need to set the notification's fireDate property to a date (An NSDate). You need a method that will convert date components to an NSDate. How about the NSCalendar method dateFromComponents:?

NSDate from week number

I am trying to create a weekly recurring local notification using Swift. Notification is going to be set to first day of every week, and in 10:00. Ofcourse I don't want to set a notification for a past date, so I need to see if now it has passed first day of week 10:00. If not, I will create notification for today 10:00, else next week monday 10:00.
I created an extension to calculate week number for current date.
extension NSDate {
func weekOfYear() -> Int {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.WeekOfYear, fromDate: self)
let weekOfYear = components.weekOfYear
return weekOfYear
}
}
I couldn't go any further than this. Any help is appreciated.
Regards.
There is an easier solution to your problem. You can use the nextDateAfterDate() method of NSCalendar:
let cal = NSCalendar.currentCalendar()
let comps = NSDateComponents()
comps.hour = 10
comps.weekday = cal.firstWeekday
let now = NSDate()
let fireDate = cal.nextDateAfterDate(now, matchingComponents: comps, options: [.MatchNextTimePreservingSmallerUnits])!
This gives the first date in the future which is at 10:00 on the first day of the week.

Resources