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
Related
func setUpLocalNotification(){
let calendar = NSCalendar(identifier: .gregorian)!
var dateFire = Date()
var fireComponents = calendar.components([NSCalendar.Unit.day,NSCalendar.Unit.month,NSCalendar.Unit.year,NSCalendar.Unit.hour,NSCalendar.Unit.minute], from: dateFire)
fireComponents.year = addAlarm.year
fireComponents.month = addAlarm.month
fireComponents.day = addAlarm.day
fireComponents.hour = addAlarm.hour
fireComponents.minute = addAlarm.minute
dateFire = calendar.date(from: fireComponents)!
let localNotification = UILocalNotification()
localNotification.fireDate = dateFire
localNotification.alertBody = addAlarm.msg
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.userInfo = ["Uid" : addAlarm.id]
UIApplication.shared.scheduleLocalNotification(localNotification)
}
I want fire notification at date in addAlarm with msg.
I did this in main.swift and not work
What should i do to work this? add this at appdelegate?
I am beginner at swift. please help...
let localNotification = UILocalNotification()
localNotification.alertBody = "Push Message"
if #available(iOS 8.2, *) {
localNotification.alertTitle = "Title"
} else {
// Fallback on earlier versions
}
let sec = 60
localNotification.fireDate = NSDate(timeIntervalSinceNow: Double(sec))
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
Here, you can put the required time at which you want to set the local push for example : sec = 60 (60 seconds).
Thank You.
let calendar = Calendar.current
let components = DateComponents(year: 2018, month: 05, day: 06, hour: 20, minute: 22) // Set the date here when you want Notification
let date = calendar.date(from: components)
let comp2 = calendar.dateComponents([.year,.month,.day,.hour,.minute], from: date!)
let trigger = UNCalendarNotificationTrigger(dateMatching: comp2, repeats: true
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 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.