Post

Replies

Boosts

Views

Activity

Reply to Adding tracks to User's Library Playlist
I've made some progress here and am drawing some assumptions, which I hope to get verified in this thread. Assumption #1: MusicDataRequest() doesn't support POST requests. I tried many different ways to do this and kept getting parsing errors when trying to pass an encoded data object in the body. So I gave up on using MusicDataRequest and went "old school" with the below. Assumption #2: As the below code results in a 400 (bad request) status and there is no additional information in the response, I assume there is something wrong with the request, most likely a bad request.httpBody entry. The below is, as best I can code in Swift right now, the same call I make in a JS app. `func addTracksToAppleMusicPlaylist(targetPlaylistId: String, tracksToAdd: [AppleMusicTracks]) async throws -> Void {   let tracks = tracksToAdd.compactMap{     AppleMusicPlaylistPostRequest(id: $0.id, type: "songs")   }   do {     print("Saving tracks to Apple Music Playlist: (targetPlaylistId)")     let tokens = try await self.getAppleMusicTokens() // <-this works correctly     if let url = URL(string: "https://api.music.apple.com/v1/me/library/playlists/\(targetPlaylistId)/tracks") {       var request = URLRequest(url: url)       request.httpMethod = "POST"       request.addValue("Bearer (tokens.devToken)", forHTTPHeaderField: "Authorization")       request.addValue("(tokens.userToken)", forHTTPHeaderField: "Music-User-Token")       request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")       let encoder = JSONEncoder()       let data = try encoder.encode(tracks)       request.httpBody = data       let session = URLSession(configuration: .default)       let task = session.dataTask(with: request) {(data, response, error) in         if error == nil {           if let httpResponse = response as? HTTPURLResponse {             print("statusCode: (httpResponse.statusCode)")             print("response: (httpResponse)"). // <= 400 response here           }         } else {           print("Error saving tracks to playlist (String(describing: error))")         }       }       task.resume()     } else {       print("Bad URL!")     }   } catch {     print("Error Saving Tracks to Playlist", error)     throw error   } }`
Topic: Media Technologies SubTopic: General Tags:
Jul ’21