问题
Trying to send a daily local notification in swift. However it just sends every minute for some reason. I want the first notification to send 30 mins after the app is opened and then repeat this notification everyday.
in the swift fie i have the following code:
//---------Daily notification code (also add section in app delagate---------- let theDate = NSDate()
let dateComp = NSDateComponents()
dateComp.minute = 30
let cal = NSCalendar.currentCalendar()
let fireDate:NSDate = cal.dateByAddingComponents(dateComp , toDate: theDate, options: NSCalendarOptions(rawValue: 0))!
let notification:UILocalNotification = UILocalNotification()
//choosing what it says in the notification and when it fires
notification.alertBody = "Your Daily Motivation is Awaits"
notification.fireDate = fireDate
UIApplication.sharedApplication().scheduleLocalNotification(notification)
//displaying notification every day
notification.repeatInterval = NSCalendarUnit.Day
//-------------end of daily notification code---------------
in my app delegate file i have the following code:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//----------daily notification section ----------
let notiftypes:UIUserNotificationType = UIUserNotificationType.Alert.union(UIUserNotificationType.Badge).union(UIUserNotificationType.Sound)
let notifSettings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notiftypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notifSettings)
return true
//----------end of daily notification section-----------
}
回答1:
The problem is that you are setting the repeat interval after scheduling the notification. Just set the notification property before scheduleLocalNotification and make sure you schedule it only once:
let notification = UILocalNotification()
notification.alertBody = "Your Daily Motivation is Awaits"
// You should set also the notification time zone otherwise the fire date is interpreted as an absolute GMT time
notification.timeZone = NSTimeZone.localTimeZone()
// you can simplify setting your fire date using dateByAddingTimeInterval
notification.fireDate = NSDate().dateByAddingTimeInterval(1800)
// set the notification property before scheduleLocalNotification
notification.repeatInterval = .Day
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Note: UIUserNotificationType are OptionSetType structures, so you can simplify its declaration also:
let notiftypes:UIUserNotificationType = [.Alert, .Badge, .Sound]
来源:https://stackoverflow.com/questions/34575786/daily-local-notification-in-swift-ios-9-2