I am working on a radio app. This is the first time and I have a problem with lock Screen Audio Card. According to docs It looks ok but could you please check why I can not display Audio Now Playing Card on lock Screen.
2 Code samples, 1. Now Playing and 2. Logic of current song and Album art.
1. Now Playing
// Create a dictionary to hold the now playing information
var nowPlayingInfo: [String: Any] = [:]
// Set the title of the current song
nowPlayingInfo[MPMediaItemPropertyTitle] = currentSong
// If album art URL is available, fetch the image asynchronously
if let albumArtUrl = albumArtUrl {
URLSession.shared.dataTask(with: albumArtUrl) { data, _, error in
if let data = data, let image = UIImage(data: data) {
// Create artwork object
let artwork = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
// Update now playing info with artwork on the main queue
DispatchQueue.main.async {
nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
} else {
// If there's an error fetching the album art, set now playing info without artwork
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
print("Error retrieving album art data:", error?.localizedDescription ?? "Unknown error")
}
}.resume()
} else {
// If album art URL is not available, set now playing info without artwork
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
}
2. Current Song, Album Art Logic
let parts = currentSong.split(separator: "-", maxSplits: 1, omittingEmptySubsequences: true).map { $0.trimmingCharacters(in: .whitespaces) }
let titleWithExtra = parts.count > 1 ? parts[1] : ""
let title = titleWithExtra.components(separatedBy: " (").first ?? titleWithExtra
return title
}
func updateSongInfo() {
let url = URL(string: "https://live.heartfm.com.tr/listen/heart_fm/currentsong")!
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data, let songString = String(data: data, encoding: .utf8) {
DispatchQueue.main.async {
self.currentSong = songString.trimmingCharacters(in: .whitespacesAndNewlines)
self.updateAlbumArtUrl(song: self.currentSong)
}
}
}.resume()
}
private func updateAlbumArtUrl(song: String) {
let parts = song.split(separator: "-", maxSplits: 1, omittingEmptySubsequences: true).map { $0.trimmingCharacters(in: .whitespaces) }
let artist = parts.first ?? ""
let titleWithExtra = parts.count > 1 ? parts[1] : ""
let title = titleWithExtra.components(separatedBy: " (").first ?? titleWithExtra
let artistAndTitle = artist.isEmpty || title.isEmpty ? song : "\(artist) - \(title)"
let encodedArtistAndTitle = artistAndTitle.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? artistAndTitle
albumArtUrl = URL(string: "https://www.heartfm.com.tr/ArtCover/\(encodedArtistAndTitle).jpg")
}