简体   繁体   English

无法及时安排本地通知在特定时间和日期触发

[英]Having trouble scheduling local notification to fire at specific time and date in swift

I am trying to schedule a notification at a certain time in swift. 我正在尝试快速地在某个时间安排通知。 My TimeString is a string that looks like 08:32 or 12:23. 我的TimeString是一个看起来像08:32或12:23的字符串。 When I try to fire on this specific date and time, the notification only fires on the specific date however not the specific time. 当我尝试在该特定日期和时间触发时,该通知仅在该特定日期触发,而不在特定时间触发。 For instance if I change the year to 2016 it won't fire. 例如,如果我将年份更改为2016,则不会触发。 If I change the month it won't fire. 如果我更改月份,则不会触发。 Yet regardless of what time I put in, if the date matches the current date, I am writing this on 1/28/2015, the notification fires regardless of time, In fact it fires as soon as I close the application as my code is in 但是无论我输入什么时间,如果日期与当前日期匹配,我都会在2015年1月8日编写该通知,无论时间如何都会触发该通知,实际上,只要我关闭代码,该通知就会立即触发在

func applicationDidEnterBackground(application: UIApplication) {
}

My code does compile so I don't think there is an error in my code. 我的代码可以编译,因此我认为代码中没有错误。

Is there any way to fire a notification at a specific time and not just a date in swift, and if so how do I implement this. 有什么方法可以在特定时间触发通知,而不仅仅是迅速地发送日期,如果是的话,我该如何实现。

            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)

Try using this approach to set your date: 尝试使用此方法设置日期:

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)

It worked for me. 它为我工作。 Hope this helps. 希望这可以帮助。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM