I'm trying to start and stop recording when my app is in background periodically. I implemented it using Timer and DispatchQueue. However whenever I am trying to initiate the recording I get this error. This issue does not exist in foreground.
Here is the current state of my app and configuration.
I have added "Background Modes" capability in the Signing & Capability and I also checked Audio and Self Care. Here is my Info.plist:
<plist version="1.0">
<dict>
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
<key>WKBackgroundModes</key>
<array>
<string>self-care</string>
</array>
</dict>
</plist>
I also used the AVAudioSession with .record category and activated it. Here is the code snippet:
func startPeriodicMonitoring() {
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSession.Category.record, mode: .default, options: [.mixWithOthers])
try session.setActive(true, options: [])
print("Session Activated")
print(session)
// Start recording.
measurementTimer = Timer.scheduledTimer(withTimeInterval: measurementInterval, repeats: true) { _ in
self.startMonitoring()
DispatchQueue.main.asyncAfter(deadline: .now() + self.recordingDuration) {
self.stopMonitoring()
}
}
measurementTimer?.fire() // Start immediately
} catch let error {
print("Unable to set up the audio session: \(error.localizedDescription)")
}
}
Any thoughts on this? I have tried most of the ways but the issue is still there.