Checked Audio in Background Modes:

enter image description here

Set up an audio session:

import UIKit import AVFoundation import MediaPlayer @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var audio: AVAudioPlayer? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: []) try audioSession.setActive(true) } catch { print(error) } do { let url = Bundle.main.url(forResource: "example", withExtension: "mp3") audio = try AVAudioPlayer(contentsOf: url!) } catch { print(error) } audio?.play() var nowPlayingInfo = [String : Any]() nowPlayingInfo[MPMediaItemPropertyArtist] = "Artist" nowPlayingInfo[MPMediaItemPropertyTitle] = "My Track" if let image = UIImage(named: "image") { nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { size in return image } } nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = audio!.currentTime nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = audio!.duration nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = audio!.rate MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo return true } } 

When the screen is locked, the sound continues to play, but the player does not appear on the locked screen. Tell me, what did not finish / not doing that?

    1 answer 1

    Add this line to the end of the application(_:didFinishLaunchingWithOptions:) function application(_:didFinishLaunchingWithOptions:) :

     UIApplication.shared.beginReceivingRemoteControlEvents() 

    So you notify the system that you want to control the player through a special menu that appears when you lock the screen.

    I also want to note that in the official documentation it is recommended to use instead of beginReceivingRemoteControlEvents() methods of the class MPRemoteCommandCenter for applications with support for iOS 7.1 and newer versions of this operating system. Below is an example of working with MPRemoteCommandCenter (use this code instead of UIApplication.shared.beginReceivingRemoteControlEvents() ):

     let commandCenter = MPRemoteCommandCenter.shared() commandCenter.playCommand.addTarget { [unowned self] event in guard let audio = self.audio else { return .commandFailed } if !audio.isPlaying { audio.play() return .success } return .commandFailed } commandCenter.pauseCommand.addTarget { [unowned self] event in guard let audio = self.audio else { return .commandFailed } if audio.isPlaying { audio.pause() return .success } return .commandFailed }