2016-07-04 2 views
1

Я пытаюсь запланировать локальное уведомление, чтобы оно произошло в 21:00 и повторялось один раз в неделю. У меня есть следующий код, и я продолжаю получать сообщение об ошибке «Не могу присвоить значение типа 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) 
} 
+0

Google dateFromComponents календарь метод –

ответ

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 
} 

Не забудьте запросить разрешение на push-уведомление.

Ссылка на мой проект я работал на https://drive.google.com/open?id=0B2csGr9uKp1DR0ViZFZMMEZSdms

0

вы должны получить дату от даты компонентов, как это:.

let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)! 
calendar.timeZone = NSTimeZone.localTimeZone() 
calendar.locale = NSLocale.currentLocale() 
let date = calendar.dateFromComponents(dateComponents)! 
Notification.fireDate = date 
Смежные вопросы