PAn Kaj Khatri
PAn Kaj Khatri

Reputation: 539

Schedule the UILocalNotifiation on same day swift

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)

Upvotes: 2

Views: 204

Answers (2)

rmaddy
rmaddy

Reputation: 318814

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.

Upvotes: 1

Twitter khuong291
Twitter khuong291

Reputation: 11692

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.

Upvotes: 1

Related Questions