2

I have successfully recorded and played the voice for the local notification sound and it also get played on calling that function.

But problem is when i give sound's link to the notification sound property, it do not work.

notification.sound = UNNotificationSound.init(named: "martian-gun copy.m4a")

Above code works perfectly. But when i gave it URL(in the form of string) it do not play the exact sound. Code not working is follows:

        let fm = FileManager.default
        let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let myurl = docsurl.appendingPathComponent("sound.m4a")

        notification.sound = UNNotificationSound.init(named: myurl)

myurl have same path at which voice play on playButton. Finally question is how to set notification custom sound from the sound URL?

Ummar Ahmed
  • 135
  • 1
  • 11

1 Answers1

1

According to the document of UNNotificationSound, you need to place a copy of your audio file in the Library/Sounds folder of your app’s container directory.

let docsurl = try FileManager.default.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myurl = docsurl.appendingPathComponent("sound.m4a")


let filename = myurl.lastPathComponent

let targetURL = try FileManager.default.soundsLibraryURL(for: filename)

// copy audio file to /Library/Sounds
if !FileManager.default.fileExists(atPath: targetURL.path) {
    try FileManager.default.copyItem(at: sourceURL, to: targetURL)
}

let content = UNMutableNotificationContent()
content.sound = UNNotificationSound(named: UNNotificationSoundName(filename))


extension FileManager {

    func soundsLibraryURL(for filename: String) throws -> URL {
        let libraryURL = try url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let soundFolderURL = libraryURL.appendingPathComponent("Sounds", isDirectory: true)
        if !fileExists(atPath: soundFolderURL.path) {
            try createDirectory(at: soundFolderURL, withIntermediateDirectories: true)
        }
        return soundFolderURL.appendingPathComponent(filename, isDirectory: false)
    }
}
Jonny
  • 1,969
  • 18
  • 25