swift iOS localNotifications

I want to set local notifications for specific times, eg : 04:30 Am Everyday, but i cant figure it out. I am new to iOS development and all localNotifications tutorials just cover fireDate = NSDate()

Thank you!

Upvotes: 0

Views: 168

Answers (1)

Twitter khuong291
Twitter khuong291

Reputation: 11702

Try this code in your function you want to fire local notification:

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 = 4
dateComponents.minute = 30
let notification = UILocalNotification()
notification.alertAction = "Title"
notification.alertBody = "Fire Fire Fire :v"
notification.repeatInterval = NSCalendarUnit.WeekOfYear
notification.fireDate = calendar.dateFromComponents(dateComponents)
UIApplication.sharedApplication().scheduleLocalNotification(notification)

And remember to put this code in your AppDelegate:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {   
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Badge, .Alert], categories: nil))
    return true
  }

Upvotes: 1

Related Questions