0

I'm new to Apple platform development, so hopefully I'm not missing anything obvious, but I can't seem to find anything on this.

I'm trying to use Apple's MusicKit service to get the JSON object for a given song, using the song's ISRC in the request. Here is Apple's documentation on the process.

Below is my attempt at this:

func getAppleMusicSongDataByISRC() async {
    let url = URL(string: "https://api.music.apple.com/v1/catalog/us/songs?filter[isrc]=\(songISRC!)")!
    let urlSession = URLSession.shared
    
    do {
        let (data, response) = try await urlSession.data(from: url)
        if let httpResponse = response as? HTTPURLResponse {
            print(httpResponse.statusCode)
        }
        self.appleMusicSongJSON = try JSONDecoder().decode(AppleMusicSongDataRoot.self, from: data)
    } catch {
        debugPrint("Error loading \(url): \(String(describing: error))")
    }
}

And here's what I received in the console when running this:

401
"Error loading https://api.music.apple.com/v1/catalog/us/songs?filter%5Bisrc%5D=GBAAA0001008: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: \"The given data was not valid JSON.\", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 \"Unable to parse empty data.\" UserInfo={NSDebugDescription=Unable to parse empty data.})))"

Clearly (according to the response code) I need to include my developer authorization token, provided by Apple. I followed the new fangled method for configuring MusicKit authorization, but I have no idea how to get that key into my Swift code.

I've tried some other things but those all require asking for access to the user's Apple Music Library. But I just want to talk to Apple's music database, not the user's. Any ideas as to how I could accomplish this?

I'm completely clueless, so any help would be greatly appreciated.

1 Answers1

0

The Apple Music API and Apple's MusicKit framework are two separate ways of fetching data from the Apple Music catalogue and user's library.

If you want to use the new method of automatically using the MusicKit token, then use the MusicKit framework. There are two different sessions at WWDC 2021 and 2022 that you can refer to.

In your case, for using the specific structure for getting the song by the ISRC value, the code is:

import MusicKit 


do {
    let songISRC = "some number here"
    let request = MusicCatalogResourceRequest<Song>(matching: \.isrc, equalTo: songISRC)
    let response = try await request.response()

    guard let song = response.items.first else { return }

    print(song)
} catch {
    print(error)
}

And that's it! You do not have to use your custom structure, as MusicKit provides a solid Song structure for you to use.

Also, in your developer portal, ensure the bundle identifier is registered and tick the MusicKit services.

Rudrank Riyam
  • 588
  • 5
  • 13