I made MPNowPlayingInfoCenter but it isn't working. Background playing is working but MPNowPlayingCenter doesn't appear. This is how I made it.
import UIKit
import AVFoundation
import MediaPlayer
class AudioPlayViewController: UIViewController, AVAudioPlayerDelegate {
var player: AVAudioPlayer!
var updater: CADisplayLink! = nil
@IBOutlet weak var playButton: UIButton!
var url_2 = URL(string: "")
var selectedFileName:String = ""
override func viewDidLoad() {
super.viewDidLoad()
let path = selectedFileName
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let url = documentsURL.appendingPathComponent(path)
url_2 = url
do {
player = try AVAudioPlayer(contentsOf: url)
updater = CADisplayLink(target: self, selector: #selector(self.trackAudio))
updater.preferredFramesPerSecond = 1
updater.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
player.prepareToPlay()
player.delegate = self
catch {
print(error)
}
let session = AVAudioSession.sharedInstance()
do{
try session.setCategory(AVAudioSession.Category.playback)
}
catch{
}
}
func play(){
player.play()
MPNowPlayingInfoCenter.default().nowPlayingInfo = [
MPMediaItemPropertyTitle: selectedFileName,
MPMediaItemPropertyArtist: "Ariana",
MPMediaItemPropertyLyrics: "test"
]
}
}
I set Background Modes > Audio, Airplay, and Pictures in picture in Targets > Signing&Capabilities.
I solved it by adding
func setupNowPlayingInfoCenter(){
UIApplication.shared.beginReceivingRemoteControlEvents()
MPRemoteCommandCenter.shared().playCommand.addTarget {event in
self.play()
return .success
}
MPRemoteCommandCenter.shared().pauseCommand.addTarget {event in
self.pause()
return .success
}
MPRemoteCommandCenter.shared().nextTrackCommand.addTarget {event in
self.goForward()
return .success
}
MPRemoteCommandCenter.shared().previousTrackCommand.addTarget {event in
self.goBackward()
return .success
}
}