Swift应用开发:如何获取Apple Music播放列表的pl格式ID?
Great question! I’ve dealt with this exact ID mismatch between user-library playlists (from MusicKit) and public Apple Music share links before—here’s how to bridge the gap:
The Core Issue
When you create a playlist in a user’s Apple Music library via MusicKit, you get a library-specific ID formatted like p.XXXXXXXX. This ID only works within the user’s library context. The pl.XXXXXXXX ID you need is the public shareable identifier, which powers the itunes.apple.com playlist links.
Step-by-Step Solutions
1. Extract the Public ID from the Playlist's url Property (MusicKit)
Once you have the Playlist instance returned from creating the user’s library playlist, you can directly access its url property. This property contains the full public Apple Music link, which includes the pl.XXXXXXXX ID.
Here’s a Swift code example:
// Assume you already have the created playlist instance (with p.XXXXXXXX ID) func getPublicPlaylistID(from playlist: Playlist) async -> String? { let request = MusicLibraryRequest<Playlist>(matching: .init(id: playlist.id)) do { let response = try await request.response() guard let userPlaylist = response.items.first, let externalUrl = userPlaylist.url else { return nil } // Parse the URL to extract the pl.XXXXXXXX segment let urlComponents = URLComponents(url: externalUrl, resolvingAgainstBaseURL: false) let pathSegments = urlComponents?.path.components(separatedBy: "/") ?? [] // The last segment in the path is the pl.XXXXXXXX ID return pathSegments.last } catch { print("Failed to fetch playlist details: \(error.localizedDescription)") return nil } } // Usage: if let publicPlId = await getPublicPlaylistID(from: yourCreatedPlaylist) { let publicShareUrl = "https://itunes.apple.com/us/playlist/your-playlist-name/\(publicPlId)?app=music" // Use this URL to open the playlist in Apple Music }
2. Use the Apple Music API Directly
If you prefer working with the raw API instead of MusicKit, you can make a GET request to the library playlists endpoint:
- Endpoint:
https://api.music.apple.com/v1/me/library/playlists/{p.XXXXXXXX-ID} - Include your app’s authorization token in the request headers.
In the response, look for the data.attributes.externalUrl field. This is the full public share link—you can parse the pl.XXXXXXXX ID from the end of its path, just like in the MusicKit example.
Key Notes
- Ensure your app has the
MusicLibraryReadWriteentitlement (configured in Xcode) to access and modify user library playlists. - The
pl.XXXXXXXXID is only generated once the playlist is synced to Apple’s servers, so there might be a small delay after creation before it’s available. Adding a short retry logic can help if you hit immediate failures.
内容的提问来源于stack exchange,提问作者jeremyms




