本地通知声音不起作用

我试图做一个闹钟应用程序,但是当我尝试做出本地通知时,我无法播放声音。 我得到这个错误:

[user info = (null)} with a sound but haven't received permission from the user to play sounds]

这里是代码:

 @IBOutlet var setAlaram: UIDatePicker! @IBAction func setAlarmButton(sender: AnyObject) { var dateformater = NSDateFormatter() dateformater.timeZone = NSTimeZone .defaultTimeZone() dateformater.timeStyle = NSDateFormatterStyle.ShortStyle dateformater.dateStyle = NSDateFormatterStyle.ShortStyle var datetimestring = NSString() datetimestring = dateformater.stringFromDate(setAlaram.date) println(datetimestring) [self .localnotification(setAlaram.date)] } func localnotification (firedate:NSDate) { var localNotification:UILocalNotification = UILocalNotification() localNotification.fireDate = firedate localNotification.alertBody = "time to woke up" localNotification.soundName = "alarm.wav" UIApplication.sharedApplication().scheduleLocalNotification(localNotification) } override func viewDidLoad() { super.viewDidLoad() let date1 = NSDate() setAlaram.date = date1 } 

你需要让用户有权在iOS 8发送本地通知。

您可以在AppDelegate方法中启动应用程序时这样做

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Sound | .Alert | .Badge, categories: nil)) return true } 

在sbarow的帮助下发布最终答案,我发现这里的解决scheme是可能对其他人有帮助的代码。

1. AppDelegate.swiftreplace这个:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Sound | .Alert | .Badge, categories: nil)) return true } 

2. ViewController.swift:

 @IBOutlet var setAlaram: UIDatePicker! @IBAction func setAlarmButton(sender: AnyObject) { var dateformater = NSDateFormatter() dateformater.timeZone = NSTimeZone .defaultTimeZone() dateformater.timeStyle = NSDateFormatterStyle.ShortStyle dateformater.dateStyle = NSDateFormatterStyle.ShortStyle var datetimestring = NSString() datetimestring = dateformater.stringFromDate(setAlaram.date) println(datetimestring) [self .localnotification(setAlaram.date)] } func localnotification (firedate:NSDate) { var localNotification:UILocalNotification = UILocalNotification() localNotification.fireDate = firedate localNotification.alertBody = "time to woke up" localNotification.soundName = "alarm.wav" UIApplication.sharedApplication().scheduleLocalNotification(localNotification) } override func viewDidLoad() { super.viewDidLoad() let date1 = NSDate() setAlaram.date = date1 }