I’m making an attempt to have Textual content() mirror the present taking part in music on my gadget (songTitle), and I can not seem to discover a solution wherever shockingly
That is my foremost handler class
let musicPlayer = MPMusicPlayerController.systemMusicPlayer
var songTitle = musicPlayer.nowPlayingItem?.title ?? "No music taking part in"
class MusicMonitor: ObservableObject {
personal let participant = MPMusicPlayerController.systemMusicPlayer
init() {
NotificationCenter.default.addObserver(
forName: .MPMusicPlayerControllerNowPlayingItemDidChange,
object: participant,
queue: OperationQueue.foremost) { (word) in
self.updateCurrentSong()
printTest(inp:("Music modified " + (self.participant.nowPlayingItem?.title ?? "No music taking part in")))
}
participant.beginGeneratingPlaybackNotifications()
updateCurrentSong() // Get preliminary music
}
personal func updateCurrentSong() {
if let nowPlayingItem = participant.nowPlayingItem {
songTitle = nowPlayingItem.title ?? "No music taking part in" // Your subsequent music logic right here
}
}
deinit {
participant.endGeneratingPlaybackNotifications()
}
}
That is largely code that I’ve pieced collectively from different boards, nevertheless it does not appear to replace in any respect when the music adjustments. It will get the music proper initially while you open the app, however by no means updates.
I’m additionally conscious there are a ton of redundant vars, I’m simply studying swift/swiftui, so I’ll return and clear it up as soon as I’m extra acquainted and I do know I will not break the whole lot
My present strive is updating it with the NotificationCenter observers however these do not appear to work. I’ve additionally tried a technique with getting the length of the music, nevertheless it type of breaks while you skip within the music. It does work updating it manually with a button press, nevertheless it does not do what I would like it to do, since ideally it does not contain consumer interplay.
Any assist could be significantly appreciated!