Please go through the below question. This can be helpful to you.
UILocalNotification custom sound is not playing in iOS7
Another thing you can try is to add .caf or .mp3 file into ImageAsset and try it.
For some reason in one of my application, I was not able to play custom sound. But after I added .mp3 file into asset folder I was able to play custom sound for remote notification.
Please try code given below.
import UIKit
import Foundation
import AudioToolbox
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, AVAudioPlayerDelegate, AlarmApplicationDelegate{
var window: UIWindow?
var audioPlayer: AVAudioPlayer?
let alarmScheduler: AlarmSchedulerDelegate = Scheduler()
var alarmModel: Alarms = Alarms()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
var error: NSError?
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch let error1 as NSError{
error = error1
print("could not set session. err:\(error!.localizedDescription)")
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch let error1 as NSError{
error = error1
print("could not active session. err:\(error!.localizedDescription)")
}
window?.tintColor = UIColor.red
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let storageController = UIAlertController(title: "Alarm", message: nil, preferredStyle: .alert)
var isSnooze: Bool = false
var soundName: String = ""
var index: Int = -1
if let userInfo = notification.userInfo {
soundName = userInfo["sound"] as! String
}
playSound(soundName)
}
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
print(notificationSettings.types.rawValue)
}
func playSound(_ soundName: String) {
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
AudioServicesAddSystemSoundCompletion(SystemSoundID(kSystemSoundID_Vibrate),nil,
nil,
{ (_:SystemSoundID, _:UnsafeMutableRawPointer?) -> Void in
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
},
nil)
let url = URL(fileURLWithPath: Bundle.main.path(forResource: soundName, ofType: "mp3")!)
var error: NSError?
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
} catch let error1 as NSError {
error = error1
audioPlayer = nil
}
if let err = error {
print("audioPlayer error \(err.localizedDescription)")
return
} else {
audioPlayer!.delegate = self
audioPlayer!.prepareToPlay()
}
audioPlayer!.numberOfLoops = -1
audioPlayer!.play()
}
}
I was able to play custom sound for local notification using above call.
This might be helpful to you.