2015-12-13 4 views
3

Я хочу установить как локальное уведомление fireDate дата моей датыPicker. Я обнаружил, что код из another answer at S.O.:Быстрое уведомление огонь от datePicker

 @IBOutlet var myDatePicker: UIDatePicker! 
     @IBOutlet var mySwitch: UISwitch! 

var localNotification = UILocalNotification() // You just need one 
var notificationsCounter = 0 

// put your functions now 
func datePicker()   { myDatePicker.datePickerMode = UIDatePickerMode.Time } 
func notificationsOptions() { 
localNotification.timeZone = NSTimeZone.localTimeZone() 
localNotification.repeatInterval = .CalendarUnitDay 
UIApplication.sharedApplication().scheduleLocalNotification(localNotification) 
localNotification.alertAction = "Open App" 
localNotification.alertBody = "Here is the seven o'clock notification" 
localNotification.soundName = UILocalNotificationDefaultSoundName 
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1 
//  you may add arbitrary key-value pairs to this dictionary. 
//  However, the keys and values must be valid property-list types 
//  if any are not, an exception is raised. 
// localNotification.userInfo = [NSObject : AnyObject]? 
} 
    func toggleSwitch(){ 
if mySwitch.on{ 
    localNotification.fireDate = myDatePicker.date 
} else { 
    localNotification.fireDate = NSDate(timeIntervalSinceNow: 999999999999)   // will never be fired 
} 
    } 
override func viewDidLoad() { 
super.viewDidLoad() 
datePicker() 
notificationsOptions() 
// Do any additional setup after loading the view, typically from a nib. 
} 

Но это не работает, даже если все кажется правильным ... где проблема ??

ответ

3

Try так:

class ViewController: UIViewController { 

    @IBOutlet var datePicker: UIDatePicker! 
    @IBOutlet var notificationSwitch: UISwitch! 

    let localNotification = UILocalNotification() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     setUpNotificationsOptions() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 

    } 

    func setUpNotificationsOptions() { 
     datePicker.datePickerMode = .Time 
     localNotification.timeZone = NSTimeZone.localTimeZone() 
     localNotification.repeatInterval = .Day 
     localNotification.alertAction = "Open App" 
     localNotification.alertBody = "a notification" 
     localNotification.soundName = UILocalNotificationDefaultSoundName 
    } 

    func toggleNotification() { 
     if notificationSwitch.on { 
      localNotification.fireDate = datePicker.date.fireDate 
      UIApplication.sharedApplication().scheduleLocalNotification(localNotification) 
     } else { 
      localNotification.fireDate = nil 
      UIApplication.sharedApplication().cancelLocalNotification(localNotification) 
     } 
    } 
    @IBAction func toggleSwitch(sender: UISwitch) { 
     toggleNotification() 
    } 
    @IBAction func dateChanged(sender: UIDatePicker) { 
     toggleNotification() 
    } 
} 

вам нужны эти расширения:

extension NSDate { 
    var minute: Int { 
     return NSCalendar.currentCalendar().component(.Minute, fromDate: self) 
    } 
    var hour: Int { 
     return NSCalendar.currentCalendar().component(.Hour, fromDate: self) 
    } 
    var day: Int { 
     return NSCalendar.currentCalendar().component(.Day, fromDate: self) 
    } 
    var month: Int { 
     return NSCalendar.currentCalendar().component(.Month, fromDate: self) 
    } 
    var year: Int { 
     return NSCalendar.currentCalendar().component(.Year, fromDate: self) 
    } 
    var fireDate: NSDate { 
     let today = NSDate() 
     return NSCalendar.currentCalendar().dateWithEra(1, 
      year: today.year, 
      month: today.month, 
      day: { hour > today.hour || (hour == today.hour 
       && minute > today.minute) ? today.day : today.day+1 }(), 
      hour: hour, 
      minute: minute, 
      second: 0, 
      nanosecond: 0 
      )! 
    } 
} 
+0

https://www.dropbox.com/s/ae8mswwz5x2p60w/localNotification.zip?dl=0 –

+0

благодарственное ты мужчина!!! «это просто работает» !!!!!! вы очень здорово, вы спасли мой день, я в долгу за это! – Swift1

+0

Теперь у меня есть проблема: весь этот код находится в контроллере «Настройки» ... но мне нужно, чтобы значение localNotification.alertBody было содержимым массива, который находится в главном viewController. если я передаю это значение, я получаю эту ошибку: использование неразрешенного идентификатора ... как я могу передать это ограничение? Можно объявить новый indexPath в контроллере настроек? – Swift1

0

Похоже, что свойство fireDate установлено только в методе toggleSwitch(). Как достигается этот метод? Я предлагаю вам переместить содержимое этого метода прямо в ваш метод notificationsOptions().

В качестве альтернативы, вы можете рассмотреть несколько более полезных имен для своих методов: datePicker() и notificationOptions(), вероятно, вызывают у вас головные боли обслуживания позже, потому что они не очень описательны.

Смежные вопросы