Reputation: 507
The app should start a sound on a specific time. To choose the specific time I used Local Notifications. Has the specific time arrived and the app is in the foreground, the sound starts and even when I close the app (background) or lock my iPhone the sound continue to play. So far so good. Now I want: Has the specific time arrived and the app is already in the background or the iPhone is locked, it should still start the sound. To achieve this, I turned the Background Modes
ON, but nothing has changed. I added mixWithOthers
to my code, still nothing happens. Any other advices?
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "NameOfFile", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: AVAudioSession.CategoryOptions.mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let player = player else { return }
player.play()
print("Start...")
} catch let error {
print(error.localizedDescription)
}
}
Background Modes: Screenshot.
This question isn't a duplicate. I search for a solution to start a sound when the iPhone is already locked/app is in the background before the sound has started. The other question is about to continue a audio in the background after the start.
Upvotes: 1
Views: 272
Reputation: 131408
You can't do what you are trying to do. If your app is in the background and more than 3 minutes has elapsed, your app will be suspended and won't get any CPU time.
You can schedule a local notification. When it fires, the system can optionally play a sound that's saved in your app bundle, or the system notification sound, and then light the screen and display a notification asking the user to open your app. You don't get called until the user decides to accept the notification.
Upvotes: 1