无法安排本地通知在swift的特定时间和日期开火

时间:2015-01-28 23:50:23

标签: ios swift notifications

我正在尝试在swift的某个时间安排通知。我的TimeString是一个看起来像08:32或12:23的字符串。当我尝试在此特定日期和时间触发时,通知仅在特定日期触发,而不是特定时间触发。例如,如果我将年份更改为2016年,则不会触发。如果我改变月份就不会开火。然而,不管我什么时候输入,如果日期与当前日期匹配,我在2015年1月28日写这个,无论时间都会触发通知,事实上,当我关闭应用程序时它会触发,因为我的代码是在

func applicationDidEnterBackground(application: UIApplication) {
}

我的代码确实编译好了,所以我认为代码中没有错误。

有没有办法在特定时间发布通知,而不仅仅是swift中的日期,如果是,我该如何实现呢。

            var timeString : String =  "2015-01-28 " + TimeString;
            println(timeString);

            let formatter = NSDateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
            formatter.timeZone = NSTimeZone(abbreviation: "GMT");
            var date = formatter.dateFromString(timeString)



            var localNotification:UILocalNotification = UILocalNotification()
            localNotification.alertAction = "Block"
            localNotification.alertBody = block.description() + " Started";
            localNotification.fireDate = date
            UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

1 个答案:

答案 0 :(得分:0)

尝试使用此方法设置日期:

let calendar = NSCalendar.currentCalendar()
    let calendarComponents = NSDateComponents()
    calendarComponents.hour = 8   //you can get you time components 
    calendarComponents.second = 0 //from your string rather than 
    calendarComponents.minute = 0 //using fixed values
    calendarComponents.day = 28
    calendarComponents.year = 2015
    calendarComponents.month = 1
    let dateToFire = calendar.dateFromComponents(calendarComponents)

它对我有用。希望这可以帮助。 :)