Notification in Swift every day at a set time? [duplicate]

萝らか妹 提交于 2019-12-05 11:54:09

First create the calendar object as you did:

var calendar = NSCalendar()
var calendarComponents = NSDateComponents()
calendarComponents.setHour(7)
calendarComponents.setSeconds(0)
calendarcomponents.setMinutes(0)
calendar.setTimeZone(NSTimeZone.defaultTimeZone)
var dateToFire = calendar.dateFromComponents(calendarComponents)

Now we can schedule the notification daily.

localNotification.fireDate = dateToFire
localNotification.setTimeZone(NSTimeZone.defaultTimeZone)
localNotification.setRepeatInterval(kcfCalendarUnitDay)

Syntax might not be perfect, I was translating from Obj-C, but you should get the general idea.

    var now = NSDate()
    var calendar = NSCalendar.currentCalendar()
    var components = calendar.components(.CalendarUnitHour | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: now)
    var d = NSCalendar.currentCalendar().dateFromComponents(components)
    if components.hour > 6 {
        d = NSDate(timeInterval: 60*60*24, sinceDate: d!)
    }


    var n = UILocalNotification()
    n.fireDate = d
    n.repeatInterval = NSCalendarUnit.CalendarUnitDay
    n.alertBody = "This is dayly notification"
    UIApplication.sharedApplication().scheduleLocalNotification(n)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!