Alex Priest Alex Priest - 8 months ago 54
iOS Question

Set Local Notification for Specific Time

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() = 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

Answer Source

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(
        localNotification.alertBody = "Hey, you must go shopping, remember?"
        localNotification.alertAction = "View List" // Change depending on your action

        localNotification.category = "reminderCategory"


//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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download