I am trying to schedule the UILocalNotifications.
The functionality i want to implement is that to repeat the notification on a perticular day, like (every monday) which will be selected by the user.
Is there any way to schedule the UILocalNotification so the notification will be trigger on that day only.
let notification = UILocalNotification()
let dict:NSDictionary = ["ID" : "your ID goes here"]
notification.userInfo = dict as! [String : String]
notification.alertBody = "\(title)"
notification.alertAction = "Open"
notification.fireDate = dateToFire
notification.repeatInterval = .Day // Can be used to repeat the notification
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(notification)
I don't sure this will help you, but I have worked with this before. I create 7 buttons to select 7 days in a week. This is my old code:
class RemindNotification {
var timerNotification = NSTimer()
func notification(story: Story) {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let date = NSDate()
let dateComponents = calendar!.components([NSCalendarUnit.Day, NSCalendarUnit.WeekOfMonth, NSCalendarUnit.Month,NSCalendarUnit.Year,NSCalendarUnit.Hour,NSCalendarUnit.Minute], fromDate:date)
dateComponents.hour = story.remindeAtHour
dateComponents.minute = story.remindeAtMinute
for index in 0..<story.remindeAtDaysOfWeek.count {
if story.remindeAtDaysOfWeek[index] == true {
if index != 6{
dateComponents.weekday = index + 2
fireNotification(calendar!, dateComponents: dateComponents)
} else {
dateComponents.weekday = 1
fireNotification(calendar!, dateComponents: dateComponents)
}
} else {
dateComponents.weekday = 0
}
}
}
func fireNotification(calendar: NSCalendar, dateComponents: NSDateComponents) {
let notification = UILocalNotification()
notification.alertAction = "Title"
notification.alertBody = "It's time to take a photo"
notification.repeatInterval = NSCalendarUnit.WeekOfYear
notification.fireDate = calendar.dateFromComponents(dateComponents)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
}
This is for my App, I can choose the day, and then it can fire LocalNotification at the specific time that I set in each day.
You can refer to it. Hope this help.
Make it a weekly by doing:
notification.repeatInterval = .Weekday // Or maybe .WeekOfYear
Whatever day of the week dateToFire is, the notification will be repeated once a week on that day of the week.
Related
So I'm currently building a schedule app and I'm trying to create a local notification to fire on specific time on specific day of the week, every week. So the first thing I do is get the date value of the start time of the event, then I subtract 5 minutes from the start time value and then schedule the notification. Previously it was very easy just had to type:
notification.repeatInterval = CalendarUnit.WeekOfYear but now the command is deprecated in Swift 3 and yeah, so the only way I found is:
let someMinutesEarlier = Calendar.current.date(byAdding: .minute, value: -5, to: startTimePicker.date)
let contentOfNotification = UNMutableNotificationContent()
let interval = someMinutesEarlier?.timeIntervalSinceNow
contentOfNotification.title = "Event starting"
contentOfNotification.body = "Some notes"
contentOfNotification.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: interval!, repeats: true)
let request = UNNotificationRequest.init(identifier: notificationIdentifier, content: contentOfNotification, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
print(error as Any)
}
but this only schedules the notification only once (no matter that the repeat boolean is set to true), because of the year in the someMinutesEarlier...or it's may be something else? Any idea?
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.
// Swift2.3
func setLNotification(weekDay:Int , hour:Int, min:Int, second:Int, alertBody:String, type:String, isRepeate:Bool){
let calender = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let dateComp: NSDateComponents?
dateComp = calender?.components([.Year,.WeekOfMonth,.Month], fromDate: NSDate())
dateComp?.hour = hour
dateComp?.minute = min
dateComp?.second = 00
dateComp?.weekday = weekDay
dateComp!.timeZone = NSTimeZone.localTimeZone()
print(calender?.dateFromComponents(dateComp!))
let SetCustomDate = calender?.dateFromComponents(dateComp!)
print(SetCustomDate)
let notification = UILocalNotification()
if isRepeate == true{
switch type {
case "Weekly":
notification.fireDate = SetCustomDate!.dateByAddingTimeInterval(60*60*24*7)
notification.repeatInterval = NSCalendarUnit.Weekday
case "2 Weekly":
notification.fireDate = SetCustomDate!.dateByAddingTimeInterval(60*60*24*14)
notification.repeatInterval = NSCalendarUnit.Day
case "Monthly":
notification.fireDate = SetCustomDate!.dateByAddingTimeInterval(60*60*24*28)
notification.repeatInterval = NSCalendarUnit.Day
default:
break;
}
notification.soundName = UILocalNotificationDefaultSoundName
notification.repeatCalendar = calender
}
notification.alertTitle = "STATS"
notification.alertBody = "Please update your Stats detail"
notification.userInfo = ["uid":"reminder"]
print(notification)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
I've got a problem with my code.
I want to set a local notification in xcode7, I'm developing a calendar where you can put your university's courses, the thing is that I'm getting the schedule from a json database and I want to notify 15 min before the class starts, but I do not know why my code is not working.
This is an example where I want to repeat the notification every Monday at 13:40.
Can I only set the day and the hour? or should I specify the month and the year too?
var dateComp:NSDateComponents = NSDateComponents()
dateComp.day = 01;
dateComp.hour = 13;
dateComp.minute = 40;
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var date:NSDate = calender.dateFromComponents(dateComp)!
let notification = UILocalNotification()
notification.fireDate = date
notification.alertBody = "Swipe to unlock"
notification.alertAction = "You've got a class soon!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["CustomField1": "w00t"]
notification.repeatInterval = NSCalendarUnit.WeekOfYear
UIApplication.sharedApplication().scheduleLocalNotification(notification)
**Weekly Local notification for swift 4
let content = UNMutableNotificationContent()
content.title = "LocalNotification"
content.subtitle = "notify"
content.body = "I am Text"
content.categoryIdentifier = "alarm"
content.badge = 1
content.sound = UNNotificationSound.default()
// Configure the recurring date.
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.weekday = 3
dateComponents.hour = 13
dateComponents.minute = 10
// Create the trigger as a repeating event.
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// 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.
print("************Error***************")
}
}
}
please check this function
func setLNotification(weekDay:Int , hour:Int, min:Int, second:Int, alertBody:String, type:String, isRepeate:Bool){
let calender = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let dateComp: NSDateComponents?
let components: NSDateComponents = NSDateComponents()
if weekDay > 0{
components.setValue(-50, forComponent: NSCalendarUnit.Year)
let previousDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!
dateComp = calender?.components([.Year,.WeekOfMonth,.Month], fromDate: previousDate)
dateComp?.hour = hour
dateComp?.minute = min
dateComp?.second = second
dateComp?.weekday = weekDay
}else{
components.setValue(hour, forComponent: NSCalendarUnit.Hour)
components.setValue(min, forComponent: NSCalendarUnit.Minute)
components.setValue(second, forComponent: NSCalendarUnit.Second)
let notifiDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!
dateComp = calender?.components([.Year,.Month,.Day,.Hour,.Minute,.Second], fromDate: notifiDate)
}
let notification = UILocalNotification()
if isRepeate == true{
notification.repeatInterval = NSCalendarUnit.WeekOfYear
notification.repeatCalendar = calender
}
notification.fireDate = calender?.dateFromComponents(dateComp!)
notification.alertBody = alertBody
notification.userInfo = ["day":"\(weekDay)","type":"\(type)"]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
I am trying to schedule a local notification so it will occur at 9:00pm and repeat once a week. I have the following code and I keep receiving a error that says "Cannot assign value of type NSDateComponents to .fireDate. I understand .fireDate will only accept NSDate types but. I can not figure out a way to set the hour variable and minute variable for a NSDate type because I don't think it is possible to do this.
func Notification(){
let dateComponents = NSDateComponents()
dateComponents.day = 4
dateComponents.month = 7
dateComponents.year = 2016
dateComponents.hour = 21
dateComponents.minute = 00
let Notification = UILocalNotification()
Notification.alertAction = "Go Back To App"
Notification.alertBody = "Did you complete your HH and QC?"
Notification.repeatInterval = NSCalendarUnit.WeekOfYear
Notification.timeZone = NSTimeZone.defaultTimeZone()
Notification.fireDate = dateComponents
UIApplication.sharedApplication().scheduleLocalNotification(Notification)
}
Here is how you do it.
Fully Tested on Swift 2.0
//Note I have taken date time from date picker
func scheduleLocalNotification() {
let localNotification = UILocalNotification()
localNotification.fireDate = fixNotificationDate(datePicker.date)
localNotification.alertBody = "Hey, you must go shopping, remember?"
localNotification.alertAction = "View List" // Change depending on your action
localNotification.category = "reminderCategory"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//This function will help you in generating fire date.
func fixNotificationDate(dateToFix: NSDate) -> NSDate {
let dateComponets: NSDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: dateToFix)
dateComponets.second = 0
let fixedDate: NSDate! = NSCalendar.currentCalendar().dateFromComponents(dateComponets)
return fixedDate
}
Don't forget to request permission for push notification.
Link to my project i worked on
https://drive.google.com/open?id=0B2csGr9uKp1DR0ViZFZMMEZSdms
You should get date from date components like this:
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone.localTimeZone()
calendar.locale = NSLocale.currentLocale()
let date = calendar.dateFromComponents(dateComponents)!
Notification.fireDate = date
I am working on a local notification for an app that should only fire on a specific day and repeat on that day until the user decided to remove it. An example notification is on that fires every Wednesday at 11:00am.
The function - scheduleLocalNotification is triggered when the user presses done on the Time picker.
var sundayNotification : UILocalNotification!
var mondayNotification : UILocalNotification!
var tuesdayNotification : UILocalNotification!
var wednesdayNotification : UILocalNotification!
var thursdayNotification : UILocalNotification!
var fridayNotification : UILocalNotification!
var saturdayNotification : UILocalNotification!
func scheduleLocalNotification() {
//Check the Dayname and match fireDate
if dayName == "Sunday" {
sundayNotification = UILocalNotification()
//timeSelected comes from the timePicker i.e. timeSelected = timePicker.date
sundayNotification.fireDate = fixNotificationDate(timeSelected)
sundayNotification.alertTitle = "Sunday's Workout"
sundayNotification.alertBody = "This is the message from Sunday's workout"
sundayNotification.alertAction = "Snooze"
sundayNotification.category = "workoutReminderID"
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.saveContext()
UIApplication.sharedApplication().scheduleLocalNotification(sundayNotification)
} else if dayName == "Monday" {
mondayNotification = UILocalNotification()
mondayNotification.fireDate = fixNotificationDate(timeSelected)
mondayNotification.alertTitle = "Monday's Workout"
mondayNotification.alertBody = "This is the message from Monday's workout"
mondayNotification.alertAction = "Snooze"
mondayNotification.category = "workoutReminderID"
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.saveContext()
UIApplication.sharedApplication().scheduleLocalNotification(mondayNotification)
} else if ..... }
}
func fixNotificationDate(dateToFix: NSDate) -> NSDate {
let dateComponets: NSDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: dateToFix)
dateComponets.second = 0
if dayName == "Sunday" {
dateComponets.weekday = 1 //n = 7
} else if dayName == "Monday" {
dateComponets.weekday = 2
} else if dayName == "Tuesday" {
dateComponets.weekday = 3
} else if dayName == "Wednesday" {
dateComponets.weekday = 4
} else if dayName == "Thursday" {
dateComponets.weekday = 5
} else if dayName == "Friday" {
dateComponets.weekday = 6
} else if dayName == "Saturday" {
dateComponets.weekday = 7
}
let fixedDate: NSDate! = NSCalendar.currentCalendar().dateFromComponents(dateComponets)
return fixedDate
}
After doing a check of the day to assign the notification the right UILocalNotification, this still strangely does not work e.g. setting different times on a different days (Sunday at 10:10am and Monday at 10:15am) for the notification does not change anything. The notification still fires on a day I did not select, i.e. Today at both those times instead of those days.
Any clues on what I could be doing wrong or missing?
Thanks in advance. :)
After some work, I came up with this. We start by changing the date to the first fire date the user selects.
func setNotificationDay(today: NSDate, selectedDay: Int) -> NSDate {
let daysToAdd: Int!
let calendar = NSCalendar.currentCalendar()
let weekday = calendar.component(.Weekday, fromDate: today)
if weekday > selectedDay {
daysToAdd = (7 - weekday) + selectedDay
} else {
daysToAdd = (selectedDay - weekday)
}
let newDate = calendar.dateByAddingUnit(.Weekday, value: daysToAdd, toDate: today, options: [])
return newDate! //if you don't have a date it'll crash
}
You can just use NSDate() instead of requiring it as a parameter. I'll leave that up to you.
Now, we need to set the notification. I didn't do anything with your fixNotificationDate(), but you can add it in easily. The key point here is to set notification.repeatInterval = .Weekday or it won't repeat. I also added a dictionary to set the day name. It's better than repeating the code as much as you did.
It does create a second call to NSCalendar, but you can probably find a way to avoid doing that in your code.
func scheduleLocalNotification(date: NSDate) {
let dayDic = [1:"Sunday",
2:"Monday",
3:"Tuesday",
4:"Wednesday",
5:"Thursday",
6:"Friday",
7:"Saturday"]
let calendar = NSCalendar.currentCalendar()
let weekday = calendar.component(.Weekday, fromDate: date)
let notification = UILocalNotification()
notification.fireDate = date
notification.repeatInterval = .Weekday
notification.alertTitle = String(format: "%#'s Workout", dayDic[weekday]!)
notification.alertBody = String(format: "This is the message from %#'s workout", dayDic[weekday]!)
notification.alertAction = "Snooze"
notification.category = "workoutReminderID"
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
And that should solve your problem. I didn't test it because it would take at least a week! ;)
Hope that helps!
I am trying to create a local notification for a reminder on a particular days in a week.
This is what I did so far to achieve
let calender = NSCalendar.currentCalendar()
let notification = UILocalNotification()
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = NSDictionary(objects: [employee.deptID!], forKeys: [“deptID”]) as [NSObject : AnyObject]
if #available(iOS 8.2, *) {
notification.alertTitle = employee.Name
} else {
}
notification.alertBody = "Its time to remind you about today’s target"
let dc = calender.components([NSCalendarUnit.Weekday , NSCalendarUnit.Hour , NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: timePicker.date)
dc.weekday = 4
notification.repeatInterval = NSCalendarUnit.Weekday // TODO :
notification.fireDate = calender.dateFromComponents(dc)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
But, the above code is triggering daily at that particular time. I want the notification to trigger at a particular time on the particular weekday.
What is the mistake in the above code ?
Try changing
notification.repeatInterval = NSCalendarUnit.Weekday
to
notification.repeatInterval = NSCalendarUnit.WeekOfYear