本地通知声音不起作用

anj*_*ani 2 audio ios uilocalnotification swift ios8

我正在尝试制作闹钟应用,但当我尝试发出本地通知时,我无法播放声音.我收到了这个错误:

[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

}
Run Code Online (Sandbox Code Playgroud)

sba*_*row 10

您需要询问用户是否允许在iOS 8中发送本地通知.

您可以在AppDelegate方法中启动应用程序时执行此操作

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

  • 我的建议是设置`localNotification.soundName = UILocalNotificationDefaultSoundName`并查看声音是否有效.如果是,那么你知道这是你的自定义声音. (3认同)