Swift iOS notification sound problems

I'm currently working on a Swift project for an iOS app that involves receiving notifications. The app is designed to play different sounds based on a specific parameter when a notification arrives. The correct behavior to follow is as follows. There are two types of notifications in the project: start notifications and stop notifications. Once the app receives a start notification it starts an audio player, the audio lasts X seconds but is looped by the player so it potentially lasts forever. When the app receives the stop notification, the player stops and the sound stops.

This works great when the app is in the foreground.

When the phone is locked and therefore the app is closed, the sound that is heard is X seconds without the sound being repeated as it happens in the foreground. Furthermore, it often happens that when the stop notification arrives, the player does not stop and continues until the end of X s time.

Does anyone have an idea of ​​how to put the loop to the sound of the notification with the phone locked and be sure that when the stop notification arrives the player stops? The sound stop works well on some devices while on others it doesn't even with the same iOS versions.

Swift iOS notification sound problems
 
 
Q