My question is the same question that I linked below but I want to do that in swift 2, not in objective-c
Fire a notification at a specific day and time every week
The problem is that the date that I'm using is by default 1st January, because I haven't specified the month, the day of the month and the year, But if I specified them it would be useless because my app wouldn't work next year, or next month
Is very simple what I want.. Set a notification weekly on Sunday (For example)
but is not practical to specify the year or the month, because it should work any Sunday or any Saturday
please help me :( I've already tried a lot
let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.hour = 2
components.minute = 54
components.weekday = 6
var newDate = calendar.dateFromComponents(components)
let notification = UILocalNotification()
notification.fireDate = newDate
notification.alertBody = "Swipe to unlock"
notification.alertAction = "You've got a class soon!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["CustomField1": "w00t"]
notification.timeZone = NSTimeZone.localTimeZone()
notification.repeatInterval = NSCalendarUnit.WeekOfYear
UIApplication.sharedApplication().scheduleLocalNotification(notification)
UPDATE:
I know it will only work on Mondays but I can fix later. The problem here is that I set the hour and minute in 0 and then it returns the current time and I do not know how to set up the hour that I want.
var pickerDate = NSDate()
print(pickerDate)
var dateComponents: NSDateComponents? = nil
var calendar = NSCalendar.currentCalendar()
dateComponents = calendar.components(NSCalendarUnit.NSWeekdayCalendarUnit, fromDate: pickerDate)
var firstMondayOrdinal = 9 - dateComponents!.weekday
dateComponents = NSDateComponents()
dateComponents!.day = firstMondayOrdinal
dateComponents?.hour = 0
dateComponents?.minute = 0
var firstMondayDate = calendar.dateByAddingComponents(dateComponents!, toDate: pickerDate, options: NSCalendarOptions(rawValue: 0))
dateComponents = NSDateComponents()
dateComponents?.weekdayOrdinal = 1
let notification = UILocalNotification()
notification.fireDate = firstMondayDate
notification.alertBody = "Swipe to unlock"
notification.alertAction = "You've got a class soon!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["CustomField1": "w00t"]
notification.timeZone = NSTimeZone.localTimeZone()
notification.repeatInterval = NSCalendarUnit.WeekOfYear
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Get the next Sunday or Monday date (SO answer), use calendar method dateBySettingHour to set the desired time to that date and use it as the firedate using the weekofyear repeat interval.