我试图制作闹钟应用,但当我尝试发出本地通知时,我无法播放声音。我收到了这个错误:
[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
}
答案 0 :(得分:10)
您需要询问用户是否允许在iOS 8中发送本地通知。
您可以在AppDelegate方法中启动应用程序时执行此操作
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Sound | .Alert | .Badge, categories: nil))
return true
}
答案 1 :(得分:2)
在sbarow的帮助下发布最终答案我发现这里的解决方案是可能对其他人有用的代码。
1. AppDelegate.swift 替换此:
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
}