ios – Refresh a var containing a tune title when the tune ends?

0
21
ios – Refresh a var containing a tune title when the tune ends?


I’m attempting to have Textual content() mirror the present enjoying tune on my gadget (songTitle), and I can not seem to discover a solution anyplace shockingly
That is my important handler class

let musicPlayer = MPMusicPlayerController.systemMusicPlayer
var songTitle = musicPlayer.nowPlayingItem?.title ?? "No tune enjoying"


class MusicMonitor: ObservableObject {
    personal let participant = MPMusicPlayerController.systemMusicPlayer
    
    init() {
        NotificationCenter.default.addObserver(
            forName: .MPMusicPlayerControllerNowPlayingItemDidChange,
            object: participant,
            queue: OperationQueue.important) { (be aware) in
                self.updateCurrentSong()
                printTest(inp:("Track modified " + (self.participant.nowPlayingItem?.title ?? "No tune enjoying")))
        }
        
        participant.beginGeneratingPlaybackNotifications()
        updateCurrentSong() // Get preliminary tune
    }
    
    personal func updateCurrentSong() {
        if let nowPlayingItem = participant.nowPlayingItem {
            songTitle = nowPlayingItem.title ?? "No tune enjoying" // Your subsequent tune logic right here
        }
    }
    
    deinit {
        participant.endGeneratingPlaybackNotifications()
    }
}

That is largely code that I’ve pieced collectively from different boards, however it would not appear to replace in any respect when the tune modifications. It will get the tune proper initially if 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 all the things

My present attempt is updating it with the NotificationCenter observers however these do not appear to work. I’ve additionally tried a way with getting the length of the tune, however it sort of breaks if you skip within the tune. It does work updating it manually with a button press, however it would not do what I would like it to do, since ideally it would not contain consumer interplay.

Any assist could be significantly appreciated!

LEAVE A REPLY

Please enter your comment!
Please enter your name here