Swift handle date change event - ios

How can I handle date change event in swift?
I want to create a set of notification when the date changes.
var localNotification: UILocalNotification = UILocalNotification()
localNotification.alertAction = "Testing notifications on iOS8"
localNotification.alertBody = " Woww it works!!"
localNotification.fireDate = date
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

You can subscribe to UIApplicationSignificantTimeChangeNotification. This one should fire when the day changes.
Unfortunately this one also fires on other occasions. So you should store a static variable with the date the last time this notification fired and then check if it actually changed the day.
I don't know what you're gonna use it for, but in most cases the general significant time change is what one is looking for.

You could do localNotification.fireDate = NSDate(timeIntervalSinceNow: 1) which will give you a notification 1 day from the current date. This could be further customized to your liking depending on how specific you want the timing to be.
EDIT: As was pointed out in the comments, the timeIntervalSinceNow is calculated in seconds, so 1 would be one second, not one day.
EDIT 2: Trying to answer the question that was asked. If you want to create a notification at midnight every day...
First, create an NSCalendar object
var calendar = NSCalendar()
var calendarComponents = NSDateComponents()
calendarComponents.setDay(29)
calendarComponents.setMonth(6)
calendarComponents.setYear(2015)
calendarComponents.setHour(12)
calendarComponents.setSeconds(0)
calendarcomponents.setMinutes(0)
calendar.setTimeZone(NSTimeZone.defaultTimeZone)
var dateToFire = calendar.dateFromComponents(calendarComponents)
Now we can schedule the notification daily.
localNotification.fireDate = dateToFire
localNotification.setTimeZone(NSTimeZone.defaultTimeZone)
localNotification.setRepeatInterval(kcfCalendarUnitDay)
Syntax might not be perfect, I was translating from Obj-C, but you should get the general idea.

Try adding observer for NSNotification.Name.NSCalendarDayChanged
The down side of this that it triggers only when app is in foreground

Related

Xamarin.iOS change local notification title automatically everyday

I'm working on a project where I need to set a different title for local notification in a specific day (lets say for Monday) with the same trigger time as the days before. How can I proceed with doing it ? I tried creating two different requests one with a repeating parameter and the other not, but then i got a duplicated notification for the "Monday" one.
Any solution to change the title for this case just only for one day and repeating ?
You have to create different UNNotificationRequest with UNCalendarNotificationTrigger and UNMutableNotificationContent to implement this.Then you will get notification with different titles in a week.
For example, create day1 like this:
UNCalendarNotificationTrigger trigger1 = UNCalendarNotificationTrigger.CreateTrigger(new NSDateComponents() { Weekday = 1, Hour = 8}, true);
UNMutableNotificationContent content1 = new UNMutableNotificationContent() { Title = "Day1", Body = "Day1", CategoryIdentifier = "Day1" };
UNNotificationRequest request1 = UNNotificationRequest.FromIdentifier("d1", content1, trigger1);

Repeating Local Notifications every Week with Swift

I have an app using local notifications there is a total of 64 notifications, which is the limit of local notifications. I need to repeat each notification every week. I know that to set the repeat interval you use:
alarm.repeatInterval = NSCalendarUnit
I have tried using the .WeekOfYear and .WeekOfMonth. Do they repeat the notification every year or month? And I do not know the calendar unit for weekly. Which one can I use to repeat weekly?
Edit:
This is the code I am using to set the notifications.
let notifyAlarm = UILocalNotification()
let component = NSDateComponents()
component.hour = NSUserDefaults.standardUserDefaults().integerForKey("Hour1")
component.minute = NSUserDefaults.standardUserDefaults().integerForKey("Minute1")
component.weekday = 1
notifyAlarm.fireDate = calendar.dateFromComponents(component)
notifyAlarm.timeZone = NSTimeZone.defaultTimeZone()
notifyAlarm.alertBody = NSUserDefaults.standardUserDefaults().stringForKey("Message1")
notifyAlarm.repeatInterval = NSCalendarUnit.WeekdayOrdinal
notifyAlarm.soundName = NSUserDefaults.standardUserDefaults().stringForKey("Sound1")
app.scheduleLocalNotification(notifyAlarm)
I am setting 64 notifications like that at once. But with different dates.
If you want the notification to fire for first time after a week you need to change the fire date.
I use TimeIntervalSinceNow for this, which is in seconds, so 1 week would be around 604000 seconds.
You can use _ to separate numbers for legibility.
alarm.fireDate = NSDate(timeIntervalSinceNow: 604_000)
Maybe a bit clunky but I think its the easiest for those type of notifications. I do something like this to make it easier.
struct NotificationFireDate {
static let nextDay: NSTimeInterval = 85_000
static let nextWeek: NSTimeInterval = 604_000
}
and than use it like so
alarm.fireDate = NSDate(timeIntervalSinceNow: NotificationFireDate.nextWeek)
Repeat interval should be weekOfYear
alarm.repeatInterval = NSCalendarUnit.WeekOfYear
The first repeating notification should fire 1 week after the first (fireDate) notification fired.
For a full list have a look at this (thanks madmik3)
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/#//apple_ref/c/tdef/NSCalendarUnit

iOS Swift Local notification not "popping up"

I'm trying to send a local notification at scheduled time. But the notifications does not appear on the screen, but it is showing in the notification center when I swipe down.
This is what I'm trying to achieve This is what I getting.
This code is from my AppDelegate's didFinishLaunchingWithOptions().
// Setup local push notifications
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil))
scheduleNotifications()
And this is the code for scheduleNotifications()
func scheduleNotifications() {
// create a corresponding local notification
let notification = UILocalNotification()
// Get today's date, time and year
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: NSDate())
// Sets the fire time to 2pm/1400 hours to anticipate user for lunch time
components.hour = 19
components.minute = 13
components.second = 00
notification.fireDate = components.date // Sets the fire date
notification.alertBody = "Enjoyed your lunch? Don't forget to track your expenses!"
notification.alertAction = "Add expense"
notification.repeatInterval = NSCalendarUnit.Day // Repeats the notifications daily
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
Any help would be appreciated. Thanks!
Your issue is the way you are converting the NSDateComponents object to an NSDate.
Simply calling components.date without setting a calendar for the NSDateComponents object will return nil.
Try using this instead:
notification.fireDate = calendar.dateFromComponents(components)
Alternatively, you can set the calendar property on the components object:
components.calendar = calendar
Because you are setting the fireDate property on the notification object to nil, it will fire immediately, i.e. before you have a chance to close the app and lock the screen. This behavour is documented in the UILocalNotification class reference
To me, when phone is connected with a cable, then notification shows up only in notification center - banner is not displayed when app is in foreground.
When cable is disconnected, then the banner is presented over the app.
I get the same odd behavior. Just created a new project to test your code.
What i noticed when you change your fireDate to:
notification.fireDate = NSDate(timeIntervalSinceNow: 10)
You will get your wanted behavior.
Hope that helps a little!
Check Settings > YourApp > Notifications.
Verify the permissions there. "Do Not Disturb" should also not be active.

UILocalNotification repeatInterval keeps pushing notifications

When using repeatInteval the notifications keep being pushed one after the other regardless if set on Minutes/Day/Hour etc.
It did seem to work fine until I tested every few seconds now settings won't change back. Any reason why ?
var dateComp:NSDateComponents = NSDateComponents()
dateComp.year = 2015;
dateComp.month = 06;
dateComp.day = 03;
dateComp.hour = 15;
dateComp.minute = 27;
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var date:NSDate = calender.dateFromComponents(dateComp)!
var notification:UILocalNotification = UILocalNotification()
notification.category = "Daily"
notification.alertBody = "OK"
notification.fireDate = date
notification.repeatInterval = NSCalendarUnit.CalendarUnitDay
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(notification)
If you set the notification to be repeated with CalendarUnitDay it should repeat each day at the same time after the first fire.
Pay attention that to delete scheduled notification is not sufficient to delete the app (at least it was in iOS7) because the system keeps the notification registered but silent for 24h to avoid accidental uninstall.
Maybe you are still seeing old scheduled notifications.
To be sure put a breakpoint and ask the app delegate for its -scheduledNotifications if you find more than you expected this is the source of your problems.
If you tested with every few seconds just once means that all notifications are scheduled and will be received. Try cancel all the scheduled notifications first and then reschedule at desired time interval
UIApplication.sharedApplication().cancelAllLocalNotifications()

Swift Background Execution at certain time each morning

I am trying to run a particular function with background execution at a certain time each morning. Here's what I have figured out...
func getCurrentTime() { //Is called every minuite by a timer
let date = NSDate()
let formatter = NSDateFormatter()
formatter.timeStyle = .ShortStyle
var stringValue = formatter.stringFromDate(date)
if stringValue == "7:00 AM" {
sendPushAlert()//Defined elsewhere in code, executes desired code
}
}
However, that does not run in the background (e.g. when app not open), and seems like a clunky way to do things.
So, How do I run background execution at a certain time each morning?
Or, is there a better way to fetch data to show in a push notification?
Thanks!!!!!!
You can't force iOS to launch your app at a specific time.
If all you want to do is send a notification at a specific time, schedule a local notification. If the user opens your notification then your app will launch.

Resources