I am trying display audio controls on the lock screen, but the problem is the audio control does not display anything in the lock screen. I already enabled background modes and the audio plays in the background.
In app delegate class, right when my app launches, I set up my audio session
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setupAudioSession()
UIApplication.shared.beginReceivingRemoteControlEvents()
return true
}
func setupAudioSession(){
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
self.becomeFirstResponder()
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
In my main controller, I call the setupLockScreen function after I play the audio.
func setupLockScreen(){
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
if self.player?.rate == 0.0 {
self.player?.play()
return .success
}
return .commandFailed
}
var nowPlayingInfo = [String : Any]()
nowPlayingInfo[MPMediaItemPropertyTitle] = "My Song"
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = audioplayerItem.duration.seconds
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = audioplayerItem.asset.duration.seconds
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player?.rate
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
I read many articles and I looked all the qustions in Stack Overflow but no luck.