I'm sorry to ask you for something like that, but I've tried this in five different ways and none of them worked. I'm currently working on an app that gives you everyday, when you awake, a little notification with an interesting fact. It takes those facts from an array that is set. I've tried to use UNNotificationCenter, UILocalNotification, etc. but I didn't succeed in writing that function. I would be glad if you could help me out with this code!
So, at 8 am, the App has to
Call the function that gives it a new fact from the array and store it in UserDefaults, lets call it newFact()
Make a notification that appears on 8 am every day, also if the phone is locked
I would be very thankful if you could help me!
Use Below Code
You can call the function here
let fact = self.newfact()
UserDefaults.standard.set(fact,forKey: "fact")
var dateComp:NSDateComponents = NSDateComponents()
dateComp.year = 2017;
dateComp.month = 04;
dateComp.day = 05;
dateComp.hour = 08;
dateComp.minute = 00;
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var date:NSDate = calender.dateFromComponents(dateComp)!
var notification:UILocalNotification = UILocalNotification()
notification.category = "Daily alarm "
notification.alertBody = fact
notification.fireDate = date
notification.repeatInterval = NSCalendarUnit.CalendarUnitDay
Related
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.
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
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
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:?
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()