如何在swift中设置每周本地通知

时间:2016-07-30 02:34:48

标签: ios swift swift2 uilocalnotification

我的代码出了问题。

我想在xcode7中设置一个本地通知,我正在开发一个日历,你可以在那里放置你的大学课程,那就是我从json数据库获取时间表,我想在15分钟之前通知课程开始,但我不知道为什么我的代码不起作用。

这是一个我希望每周一13:40重复通知的例子。

我可以只设定日期和时间吗?还是我应该指定月份和年份?

  var dateComp:NSDateComponents = NSDateComponents()

    dateComp.day = 01;
    dateComp.hour = 13;
    dateComp.minute = 40;
    dateComp.timeZone = NSTimeZone.systemTimeZone()

    var calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    var date:NSDate = calender.dateFromComponents(dateComp)!

    let notification = UILocalNotification()
    notification.fireDate = date
    notification.alertBody = "Swipe to unlock"
    notification.alertAction = "You've got a class soon!"
    notification.soundName = UILocalNotificationDefaultSoundName
    notification.userInfo = ["CustomField1": "w00t"]
    notification.repeatInterval = NSCalendarUnit.WeekOfYear

    UIApplication.sharedApplication().scheduleLocalNotification(notification)

2 个答案:

答案 0 :(得分:0)

请检查此功能

func setLNotification(weekDay:Int , hour:Int, min:Int, second:Int, alertBody:String, type:String, isRepeate:Bool){
    let calender = NSCalendar(identifier: NSCalendarIdentifierGregorian)
    let dateComp: NSDateComponents?
    let components: NSDateComponents = NSDateComponents()

    if weekDay > 0{
        components.setValue(-50, forComponent: NSCalendarUnit.Year)

        let previousDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!
        dateComp = calender?.components([.Year,.WeekOfMonth,.Month], fromDate: previousDate)
        dateComp?.hour = hour
        dateComp?.minute = min
        dateComp?.second = second
        dateComp?.weekday = weekDay
    }else{
        components.setValue(hour, forComponent: NSCalendarUnit.Hour)
        components.setValue(min, forComponent: NSCalendarUnit.Minute)
        components.setValue(second, forComponent: NSCalendarUnit.Second)
        let notifiDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!
        dateComp = calender?.components([.Year,.Month,.Day,.Hour,.Minute,.Second], fromDate: notifiDate)
    }

    let notification = UILocalNotification()
    if isRepeate == true{
        notification.repeatInterval = NSCalendarUnit.WeekOfYear
        notification.repeatCalendar = calender
    }
    notification.fireDate = calender?.dateFromComponents(dateComp!)
    notification.alertBody = alertBody
    notification.userInfo = ["day":"\(weekDay)","type":"\(type)"]

    UIApplication.sharedApplication().scheduleLocalNotification(notification)
}

答案 1 :(得分:0)

**每周4快速通知本地通知

<style name="MyRadioButtonStyle" 
     parent="@android:style/Widget.CompoundButton.RadioButton">
            <item name="android:button">@drawable/radio_btn_selector</item>
        </style>

//配置重复日期。

javascript.min