unauthorized request in integration with Apple Music API

Hello Apple Developer community,

I'm currently facing an issue with the integration of the Apple Music API in my application. I've followed the documentation and guidelines provided by Apple, but I'm encountering problems with authentication and parsing the Apple Music track details.

Here's a summary of the issue:

When making a request to fetch Apple Music track details using the provided API endpoint, I'm receiving the following error: "Error parsing Apple Music track details: The data couldn't be read because it isn't in the correct format." Additionally, the response status code is 401, indicating an unauthorized request.

I have already tried the following troubleshooting steps:

Verified that the MusicKit App Service is enabled in my app's App ID configuration. Confirmed that the bundle identifier used in the app matches the one in the App ID configuration. Ensured that I'm signed in with a valid Apple ID in the simulator and device I'm testing.

Despite these efforts, the issue persists. I believe I have followed the correct procedures for automatic developer token generation, but there might be something missing or misconfigured.

I'm seeking assistance and guidance from the Stack Overflow community on how to resolve this issue. Any insights, suggestions, or troubleshooting steps would be greatly appreciated.

Thank you in advance for your help!


 func fetchAppleMusicTrackDetails(from mediaURL: URL, completion: @escaping (AppleMusicTrack?) -> Void) {
        let components = URLComponents(url: mediaURL, resolvingAgainstBaseURL: false)
        guard let itemID = components?.queryItems?.first(where: { $0.name == "id" })?.value else {
            completion(nil)
            return
        }
        
        fetchStorefront { storefront in
            guard let storefront = storefront else {
                print("storefront issue")
                completion(nil)
                return
            }

            let regex = try! NSRegularExpression(pattern: "\\s*\\(.*?\\)\\s*", options: .caseInsensitive)
            let trimmedStorefront = regex.stringByReplacingMatches(in: storefront, options: [], range: NSMakeRange(0, storefront.count), withTemplate: "")

            let encodedStorefront = trimmedStorefront.replacingOccurrences(of: " ", with: "%20")
            let lookupURLString = "https://api.music.apple.com/v1/catalog/\(encodedStorefront)/songs/\(itemID)"
            print(lookupURLString)
            guard let lookupURL = URL(string: lookupURLString) else {
                print("lookupURL issue")
                completion(nil)
                return
            }
            
            
            
            URLSession.shared.dataTask(with: lookupURL) { (data, response, error) in
                if let httpResponse = response as? HTTPURLResponse {
                    print("Status code: \(httpResponse.statusCode)")
                }

                if let error = error {
                    print("Error fetching Apple Music track details: \(error.localizedDescription)")
                    completion(nil)
                    return
                }
                
                guard let data = data else {
                    completion(nil)
                    print("no data")
                    return
                }
                let responseString = String(data: data, encoding: .utf8)
                print("Response data: \(responseString ?? "No data")")

                do {
                    let responseJSON = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                    let results = responseJSON?["results"] as? [[String: Any]]
                    let trackData = results?.first
                    print(responseJSON)
                    // Extract the necessary track information from the JSON response
                    guard let title = trackData?["trackName"] as? String,
                          let artist = trackData?["artistName"] as? String,
                          let album = trackData?["collectionName"] as? String,
                          let artworkURLString = trackData?["artworkUrl100"] as? String,
                          let artworkURL = URL(string: artworkURLString),
                          let trackURLString = trackData?["previewUrl"] as? String,
                          let trackURL = URL(string: trackURLString) else {
                        completion(nil)
                        return
                    }
                    
                    // Download the artwork image
                    URLSession.shared.dataTask(with: artworkURL) { (artworkData, _, _) in
                        guard let artworkData = artworkData, let artworkImage = UIImage(data: artworkData) else {
                            completion(nil)
                            return
                        }
                        
                        let track = AppleMusicTrack(title: title, artist: artist, album: album, artwork: artworkImage, trackURL: trackURL)
                        completion(track)
                    }.resume()
                } catch {
                    print("Error parsing Apple Music track details: \(error.localizedDescription)")
                    completion(nil)
                }
            }.resume()

            }
    }
    
    func fetchStorefront(completion: @escaping (String?) -> Void) {
        SKCloudServiceController().requestStorefrontCountryCode { storefrontCountryCode, error in
            if let error = error {
                print("Error fetching storefront country code: \(error.localizedDescription)")
                completion(nil)
                return
            }
            
            guard let countryCode = storefrontCountryCode else {
                print("country code error")
                completion(nil)
                return
            }
            
            completion(countryCode)
        }
    }