为特定时间设置本地通知

时间:2016-07-04 22:38:18

标签: ios xcode swift nsdatecomponents localnotification

我正在尝试安排本地通知,因此它将在晚上9点发生,并且每周重复一次。我有以下代码,我一直收到一个错误,上面写着“无法将NSDateComponents类型的值赋给.fireDate。我明白.fireDate只会接受NSDate类型但是。我无法想出一种设置小时变量和分钟变量的方法对于NSDate类型,因为我认为不可能这样做。

func Notification(){

    let dateComponents = NSDateComponents()
    dateComponents.day = 4
    dateComponents.month = 7
    dateComponents.year = 2016
    dateComponents.hour = 21
    dateComponents.minute = 00

    let Notification = UILocalNotification()

    Notification.alertAction = "Go Back To App"
    Notification.alertBody = "Did you complete your HH and QC?"
    Notification.repeatInterval = NSCalendarUnit.WeekOfYear
    Notification.timeZone = NSTimeZone.defaultTimeZone()

    Notification.fireDate = dateComponents
    UIApplication.sharedApplication().scheduleLocalNotification(Notification)
}

2 个答案:

答案 0 :(得分:1)

这是你如何做到的。

  

在Swift 2.0上完全测试

//注意我从日期选择器中取出了日期时间

   func scheduleLocalNotification() {
        let localNotification = UILocalNotification()

        localNotification.fireDate = fixNotificationDate(datePicker.date)
        localNotification.alertBody = "Hey, you must go shopping, remember?"
        localNotification.alertAction = "View List" // Change depending on your action

        localNotification.category = "reminderCategory"

        UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    }

//此功能可以帮助您生成开火日期。

func fixNotificationDate(dateToFix: NSDate) -> NSDate {
    let dateComponets: NSDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: dateToFix)

    dateComponets.second = 0

    let fixedDate: NSDate! = NSCalendar.currentCalendar().dateFromComponents(dateComponets)

    return fixedDate
}

不要忘记请求推送通知权限。

链接到我工作的项目 https://drive.google.com/open?id=0B2csGr9uKp1DR0ViZFZMMEZSdms

答案 1 :(得分:0)

您应该从日期组件中获取日期,如下所示:

let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone.localTimeZone()
calendar.locale = NSLocale.currentLocale()
let date = calendar.dateFromComponents(dateComponents)!
Notification.fireDate = date