I regularly run the background thread scheduledTimerWithTimeInterval() , which checks for records in the database with a certain status
If there are such records, then you need to play mp3.
Did playback using:
1. AVAudioPlayer
Enabled Audio, AirPlay and Picture in Picture в BackgroundModes
do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().setActive(true) } catch _ { return print("error") } Set category AVAudioSessionCategoryPlayback
Problem: a sound is played every 20 seconds on the open screen (music plays), but when I just turn off the application, the sound itself is no longer playing.
2. AudioServicesPlayAlertSound (1009)
It worked but APPLE was rejected with the reason " backgroundModes mode is on but nothing is played."
What can be used for such a task?
UPD
This is the method that starts the timer at intervals of 20 seconds:
func scheduledTimerWithTimeInterval(){ timer = NSTimer.scheduledTimerWithTimeInterval(20, target: self, selector: #selector(ListOfOrders.checkNewOrder), userInfo: nil, repeats: true) registerBackgroundTask() } This is the method that starts the timer in which the data is downloaded and validated. If there is new data, in theory the phone should squeak
func checkNewOrder() { WorkWithInternet().getOrders(self, token: prefs.stringForKey("token")!, col: 0, add: false, vc: ListOfOrders()) } UPD2 Play sound by file:
do { let soundURL: NSURL = NSBundle.mainBundle().URLForResource("notif", withExtension: "mp3")! audioPlayer = try AVAudioPlayer(contentsOfURL: soundURL) audioPlayer!.delegate = self audioPlayer!.prepareToPlay() audioPlayer!.play() }catch{ print("Error") } UPD3
var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid Register a task in the background:
func registerBackgroundTask() { backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { [unowned self] in self.endBackgroundTask() } assert(backgroundTask != UIBackgroundTaskInvalid) } Background termination task function:
func endBackgroundTask() { NSLog("Background task ended.") UIApplication.sharedApplication().endBackgroundTask(backgroundTask) backgroundTask = UIBackgroundTaskInvalid }