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

删除回忆录丶 提交于 2019-12-07 06:58:05

问题


If anyone gets confused and thinks that this is a duplicate of my question from yesterday, it's not. There I was asking how to call a function every day, here I am asking how to call a notification at a specific time every day.

I am looking for a way to repeat a local notification every day at 7.00AM. I currently have this code setup to get the day, month, year etc.

let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: date)
    let hour = components.hour
    let minutes = components.minute
    let month = components.month
    let year = components.year
    let day = components.day

How do I call a notification every day when the time is 7.00 AM?


回答1:


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.




回答2:


    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)


来源:https://stackoverflow.com/questions/31170112/notification-in-swift-every-day-at-a-set-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!