1

So i am using the following .swift file to get notification showing the media player controls on the lock screen and notification screen. The following code works fine on iOS but not on iPad.

I have uploaded the full code to Github https://github.com/redimongo/DRN1

The part in question is what do I need to add for the iPad to get media control?

//
//  MusicPlayer.swift
//  DRN1
//
//  Created by Russell Harrower on 25/11/19.
//  Copyright © 2019 Russell Harrower. All rights reserved.
//

import Foundation
import AVFoundation
import MediaPlayer
import Kingfisher

class MusicPlayer {
    static let shared = MusicPlayer()
    var player: AVPlayer?


        func startBackgroundMusic() {

            self.setupRemoteTransportControls()
            let urlString = "http://stream.radiomedia.com.au:8003/stream"
            guard let url = URL.init(string: urlString)
                else {
                    return
            }
            let playerItem = AVPlayerItem.init(url: url)
            player = AVPlayer.init(playerItem: playerItem)



            player?.play()

            do {
              //  try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
                try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.duckOthers, .defaultToSpeaker, .mixWithOthers, .allowAirPlay])
                print("Playback OK")
                let defaults = UserDefaults.standard
                defaults.set("1", forKey: defaultsKeys.musicplayer_connected)
                try AVAudioSession.sharedInstance().setActive(true)
                print("Session is Active")
            } catch {
                let defaults = UserDefaults.standard
                defaults.set("0", forKey: defaultsKeys.musicplayer_connected)
                print(error)
            }

        }




    func setupRemoteTransportControls() {
       // Get the shared MPRemoteCommandCenter
        let commandCenter = MPRemoteCommandCenter.shared()

        // Add handler for Play Command
        commandCenter.playCommand.addTarget { [unowned self] event in
            if self.player?.rate == 0.0 {
                self.player?.play()
                return .success
            }
            return .commandFailed
        }

        // Add handler for Pause Command
        commandCenter.pauseCommand.addTarget { [unowned self] event in
            if self.player?.rate == 1.0 {
                self.player?.pause()
                return .success
            }
            return .commandFailed
        }

       // self.nowplaying(artist: "Anna", song: "test")


    }

    func nowplaying(with artwork: MPMediaItemArtwork, artist: String, song: String){

    MPNowPlayingInfoCenter.default().nowPlayingInfo = [
          MPMediaItemPropertyTitle:song,
          MPMediaItemPropertyArtist:artist,
          MPMediaItemPropertyArtwork: artwork,
          MPNowPlayingInfoPropertyIsLiveStream: true
    ]


       // self.getArtBoard();
    }


    func setupNowPlayingInfo(with artwork: MPMediaItemArtwork) {
          MPNowPlayingInfoCenter.default().nowPlayingInfo = [
            //   MPMediaItemPropertyTitle: "Some name",
            //   MPMediaItemPropertyArtist: "Some name",
               MPMediaItemPropertyArtwork: artwork,
               //MPMediaItemPropertyPlaybackDuration: CMTimeGetSeconds(currentItem.duration),
               //MPNowPlayingInfoPropertyPlaybackRate: 1,
               //MPNowPlayingInfoPropertyElapsedPlaybackTime: CMTimeGetSeconds(currentItem.currentTime())
           ]
       }



    func getData(from url: URL, completion: @escaping (UIImage?) -> Void) {
        URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) in
            if let data = data {
                completion(UIImage(data:data))
            }
        })
            .resume()
    }

    func getArtBoard(artist: String, song: String, cover: String) {
        guard let url = URL(string: cover) else { return }
        getData(from: url) { [weak self] image in
            guard let self = self,
                let downloadedImage = image else {
                    return
            }
            let artwork = MPMediaItemArtwork.init(boundsSize: downloadedImage.size, requestHandler: { _ -> UIImage in
                return downloadedImage
            })
            self.nowplaying(with: artwork, artist: artist, song: song)
        }
    }



        func stopBackgroundMusic() {
            guard let player = player else { return }
            player.pause()

    }


}

I have added with no success

override func viewDidLoad() {



        UIApplication.shared.beginReceivingRemoteControlEvents()
               do {
                    try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
                    try AVAudioSession.sharedInstance().setActive(true)
                } catch {
                    print(error)
                }
}
3
  • Unless I'm missing the real problem here, running your project on an iPad shows transport controls just fine. They are working as expected even when the app is in the background. Here is a screenshot: imgur.com/cfw1eOM
    – Alladinian
    Dec 24, 2019 at 9:46
  • @alladinian is that in simulator? Because on iPad 7 simulator it does not work even Apple is saying it does not. I need specs. Dec 24, 2019 at 14:23
  • This is from a real device (iPad 6th gen / 2018 / 9.7")
    – Alladinian
    Dec 24, 2019 at 21:47

2 Answers 2

2
+500

iOS simulators running iOS11+ (including iPadOS) will not show remote control center unless if it’s the default controls created by AVPlayerController. You will need a real device to test MPRemoteCommandCenter or install iOS 10 and lower to run it on simulator.

    override func viewDidLoad() {          
       super.viewDidLoad()
         // This is an alternative 
        let avPlayerViewController = AVPlayerViewController()           
        avPlayerViewController.player = MusicPlayer.shared.player
        avPlayerViewController.player?.play() 

    #if targetEnvironment(simulator)
        /*
       if you don’t set up remote controls, the AVPlayer from 
       AVPlayerController will immediately create default remote controls
       otherwise your simulator will not show the controls.
                 */


    #else

     MusicPlayer.shared.setupRemoteTransportControls()
     // more custom controls set up

    #endif

     }

Also there is also no need to call UIApplication.shared.beginReceivingRemoteControlEvents() on devices running iOS 7 and later.

**EDIT : **

    —— In your MusicPlayer Class —

   import Foundation
   import AVFoundation
   import MediaPlayer

   import AVKit

class MusicPlayer {
static let shared = MusicPlayer()


var player: AVPlayer?
let playerViewController = AVPlayerViewController()


    func startBackgroundMusic() {


        let urlString = "http://stream.radiomedia.com.au:8003/stream"
        guard let url = URL.init(string: urlString) else { return }

        let playerItem = AVPlayerItem.init(url: url)
        player = AVPlayer.init(playerItem: playerItem)

        do {

            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.duckOthers, .defaultToSpeaker, .mixWithOthers, .allowAirPlay])
            print("Playback OK")
           // let defaults = UserDefaults.standard
           // defaults.set("1", forKey: defaultsKeys.musicplayer_connected)
            try AVAudioSession.sharedInstance().setActive(true)
            print("Session is Active")
        } catch {
           // let defaults = UserDefaults.standard
          //  defaults.set("0", forKey: defaultsKeys.musicplayer_connected)
            print(error)
        }

         #if targetEnvironment(simulator)

         if playerViewController.player == nil {
        playerViewController.player = player
        }
        playerViewController.player?.play()
        print("SIMULATOR")

         #else

        self.setupRemoteTransportControls()
        player?.play()

        #endif

    }




func setupRemoteTransportControls() {
   // Get the shared MPRemoteCommandCenter
    let commandCenter = MPRemoteCommandCenter.shared()

    // Add handler for Play Command
    commandCenter.playCommand.addTarget { [unowned self] event in
        if self.player?.rate == 0.0 {
            self.player?.play()
            return .success
        }
        return .commandFailed
    }

    // Add handler for Pause Command
    commandCenter.pauseCommand.addTarget { [unowned self] event in
        if self.player?.rate == 1.0 {
            self.player?.pause()
            return .success
        }
        return .commandFailed
    }

   // self.nowplaying(artist: "Anna", song: "test")


}

func nowplaying(with artwork: MPMediaItemArtwork, artist: String, song: String){

MPNowPlayingInfoCenter.default().nowPlayingInfo = [
      MPMediaItemPropertyTitle:song,
      MPMediaItemPropertyArtist:artist,
      MPMediaItemPropertyArtwork: artwork,
      MPNowPlayingInfoPropertyIsLiveStream: true
]


   // self.getArtBoard();
}


func setupNowPlayingInfo(with artwork: MPMediaItemArtwork) {
      MPNowPlayingInfoCenter.default().nowPlayingInfo = [
        //   MPMediaItemPropertyTitle: "Some name",
        //   MPMediaItemPropertyArtist: "Some name",
           MPMediaItemPropertyArtwork: artwork,
           //MPMediaItemPropertyPlaybackDuration: CMTimeGetSeconds(currentItem.duration),
           //MPNowPlayingInfoPropertyPlaybackRate: 1,
           //MPNowPlayingInfoPropertyElapsedPlaybackTime: CMTimeGetSeconds(currentItem.currentTime())
       ]
   }



func getData(from url: URL, completion: @escaping (UIImage?) -> Void) {
    URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) in
        if let data = data {
            completion(UIImage(data:data))
        }
    })
        .resume()
}

func getArtBoard(artist: String, song: String, cover: String) {
    guard let url = URL(string: cover) else { return }
    getData(from: url) { [weak self] image in
        guard let self = self,
            let downloadedImage = image else {
                return
        }
        let artwork = MPMediaItemArtwork.init(boundsSize: downloadedImage.size, requestHandler: { _ -> UIImage in
            return downloadedImage
        })
        self.nowplaying(with: artwork, artist: artist, song: song)
    }
}



     func stopBackgroundMusic() {
        #if targetEnvironment(simulator)

     if  playerViewController.player != nil {
        playerViewController.player?.pause()
                   }

      #else

      guard let player = player else { return }
      player.pause()

      #endif

}



}

Tested it using iPadOS Simulator (7th Generation)

6
  • I tried your code and in simulator it still did not show the media controls. Dec 27, 2019 at 5:35
  • Could I ask you clone my github project and test your code and if you can get it to work upload it please. I am sure your answer is correct. Dec 27, 2019 at 6:38
  • You just have to modify your MusicPlayer class. I tested the code, it is working on iPadOS simulator
    – Celeste
    Dec 27, 2019 at 17:21
  • I must be doing something wrong then because I am running Version 11.2.1 (SimulatorApp-912.4 SimulatorKit-570.3 CoreSimulator-681.15) & Model: iPad (7th generation) iOS 13.2.2 (17B102) and it is not showing the controls. Is iPadOS Simulator an app as that seems different to what I am using Dec 28, 2019 at 2:53
  • How are you presenting the playerViewController though? The controls will be shown once you present it. Try this : let musicPlayer = MusicPlayer.shared present(musicPlayer.playerViewController, animated: true) The only thing that’s not being shown is the art work.
    – Celeste
    Dec 28, 2019 at 6:54
-1

Also, you can use the Media Player framework’s MPRemoteCommandCenter and MPNowPlayingInfoCenter classes with AVPlayer.

You need to invoke beginReceivingRemoteControlEvents()

Swift 3+

UIApplication.sharedApplication().beginReceivingRemoteControlEvents() 
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)

If you would like to specify custom actions for the MPRemoteCommandCenter:

let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget(self, action:#selector(nextTrackCommandSelector))

For more information refer Apple's official Documentation

2
  • where do I put these tho - and is this just for iPad? Dec 24, 2019 at 5:16
  • do I do it like this func applicationDidFinishLaunching(_ application: UIApplication) { UIApplication.shared.beginReceivingRemoteControlEvents() AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) } Dec 24, 2019 at 5:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.