I am developing a SwiftUI application and I am having the hardest time (as in I have been completely unable) to get meta data from SoundCloud. The SoundCloud app is populating control center with the metadata so I should be able to access it.
I am able to get the metadata from Apple Music for example using let musicPlayer = MPMusicPlayerController.systemMusicPlayer
. Any 3rd party app need to be using: let nowPlayingInfo = MPNowPlayingInfoCenter.default().nowPlayingInfo
.
I have added the permissions for Media Library access and Apple Music.
I just need to know if it is possible as technically it should be. All the posts concerning it are from iOS 6 or 11 years ago. Any help would be much appreciated.
import MediaPlayer
class NowPlayingMetadataObserver: ObservableObject {
@Published var songTitle: String = "Unknown Title"
@Published var artistName: String = "Unknown Artist"
@Published var albumTitle: String = "Unknown Album"
init() {
// OBSERVE CHANGES IN NOW PLAYING
NotificationCenter.default.addObserver(
self,
selector: #selector(handleNowPlayingInfoChange),
name: NSNotification.Name.MPNowPlayingInfoCenterNowPlayingInfoDidChange,
object: nil
)
}
@objc private func handleNowPlayingInfoChange() {
if let nowPlayingInfo = MPNowPlayingInfoCenter.default().nowPlayingInfo {
songTitle = nowPlayingInfo[MPMediaItemPropertyTitle] as? String ?? "Unknown Title"
artistName = nowPlayingInfo[MPMediaItemPropertyArtist] as? String ?? "Unknown Artist"
albumTitle = nowPlayingInfo[MPMediaItemPropertyAlbumTitle] as? String ?? "Unknown Album"
} else {
songTitle = "No song playing"
artistName = "Unknown Artist"
albumTitle = "Unknown Album"
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// DISPLAY THE RESULT WHEN 3RD PARTY APP IS PLAYING
struct ContentView: View {
@StateObject private var metadataObserver = NowPlayingMetadataObserver()
var body: some View {
VStack(spacing: 20) {
Text("Now Playing:")
.font(.headline)
Text(metadataObserver.songTitle)
.font(.title)
.bold()
Text("Artist: (metadataObserver.artistName)")
.font(.subheadline)
Text("Album: (metadataObserver.albumTitle)")
.font(.subheadline)
}
.padding()
}
}
Michael Pinchin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.