If an app allows people to create a playlist and add more songs to that created playlist, it would make sense to guard them from accidentally adding the same song to the playlist more than once.
In this code, even though it is successfully receiving the existing playlist from the request, its tracks and entries always show as nil even when there are songs in the playlist.
Any suggestions for how to guard against adding duplicates to a playlist? Thank you!
var request = MusicLibraryRequest<Playlist>()
request.filter(matching: \.name, equalTo: "AppGeneratedPlaylist")
let response = try await request.response()
if let existingPlaylist = response.items.first {
if let tracks = existingPlaylist.entries, tracks.contains(where: { $0.id == song.id }) {
print("Song is already in the playlist, so don't add again")
return
} else {
try await MusicLibrary.shared.add(song, to: existingPlaylist)
print("Added song to existing playlist: \(existingPlaylist.name)")
print("Count of tracks: \(existingPlaylist.tracks?.count)")
print("Count of entries: \(existingPlaylist.entries?.count)")
print("Current tracks: \(existingPlaylist.tracks?.map(\.id))")
print("Current entries: \(existingPlaylist.entries?.map(\.id))")
}
}
1
0
31