我希望触发本地通知。我尝试创建它,但是成功了,没有任何错误,但是当我在模拟器中运行应用程序时,本地通知无法执行
app delegate中的代码

application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert | .Badge | .Sound, categories: nil))

  // play default sound
    return true
}

view controller
class TechByteSchedulingViewController:UIViewController {
@IBOutlet weak var datePicker: UIDatePicker!

@IBAction func DateChosen(sender: UIButton) {
    func sendNotification(sender: UIButton) {
        var localNotification = UILocalNotification()
        localNotification.fireDate = datePicker.date
        localNotification.repeatInterval = .CalendarUnitDay
        localNotification.alertBody = "check out your daily byte"
        localNotification.alertAction = "Open"
        localNotification.timeZone = NSTimeZone.defaultTimeZone()
        localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
        localNotification.soundName = UILocalNotificationDefaultSoundName
        UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

        func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
            application.applicationIconBadgeNumber = 0

    }
        self.navigationController?.popToRootViewControllerAnimated(true)
            }

}
override func viewDidDisappear(animated: Bool) {


}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

最佳答案

根据我所看到的,您在ButtonAction函数内部实现了某些功能,这是错误的...您应该在之外实现 sendNotfication 函数,然后在外部实现它,然后在内将其调用ButtonAction

class TechByteSchedulingViewController:UIViewController  {

   @IBOutlet weak var datePicker: UIDatePicker!

  @IBAction func DateChosen(sender: UIButton) {
    self.sendNotification()
  }

    func sendNotification() {
    var localNotification = UILocalNotification()
    localNotification.fireDate = datePicker.date
    localNotification.repeatInterval = .CalendarUnitDay
    localNotification.alertBody = "check out your daily byte"
    localNotification.alertAction = "Open"
    localNotification.timeZone = NSTimeZone.defaultTimeZone()
    localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
    localNotification.soundName = UILocalNotificationDefaultSoundName
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
 }

    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
        application.applicationIconBadgeNumber = 0
    self.navigationController?.popToRootViewControllerAnimated(true)
        }

    }

08-06 13:30