Home > OS >  iOS Custom Notification Sound (UNNotificationSound) doesn't play when iPhone is locked
iOS Custom Notification Sound (UNNotificationSound) doesn't play when iPhone is locked

Time:06-21

My app uses remote notifications with a NotificationService Extension in which I edit the notification before displaying it. I would like to let the user upload a custom sound file which should be played instead of the default sound. For this I use an shared AppGroup, which the app and the extension have access to.

The uploaded sound files are stored in the "Library/Sounds" directory as follows (my code for testing, without much error handling):

.....

let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.xxx.xxx")
        let soundsURL = containerURL!.appendingPathComponent("Library/Sounds/", isDirectory: true)

        if !FileManager.default.fileExists(atPath: soundsURL.path) {
            try! FileManager.default.createDirectory(atPath: soundsURL.path, withIntermediateDirectories: true)
        }

        if FileManager.default.fileExists(atPath: soundsURL.path) {
            do {
                try FileManager.default.copyItem(at: sourceURL, to: soundsURL.appendingPathComponent(sourceURL.lastPathComponent))
            } catch {
                // Exception
            }
        }

In the Notification Extension I change the sound of the notification to the name of the uploaded file:

bestAttemptContent.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "test.wav"))

This is working fine as long as the iPhone is not locked. But if the iPhone is locked, there is no vibration and no sound is played (also no default sound). But I don't know why - according to apples documentation UNNotificationSound looks in "Library/Sounds" of the app shared group container directories. If I store the file directly in the main bundle, it works.

Does anyone have any idea what could be causing this?

CodePudding user response:

Ok, now i figured out what the problem is.

My files were created with "NSFileProtectionComplete" data protection by default.

"NSFileProtectionComplete — The file is only accessible while the device is unlocked."

After changing the data protection of my sound files to "NSFileProtectionNone", it finally works!

  • Related