anjani anjani - 11 months ago 86
Swift Question

Local notification sound not working

I'm trying to make an alarm app but when I try to make a local notification I am unable to play the sound. I got this error:

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


Here is the code:

@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

}

Answer Source

You need to ask the user for permission to send local notifications in iOS 8.

You can do so when you application launches in your AppDelegate methods

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