Apple Music API 需要开发者令牌和用户令牌。虽然问题是关于 python 的,但这个答案是为未来遇到这个问题的快速开发人员准备的。
例如,
static func addPlaylistPathURLString(developerToken: String, userToken: String) -> URLRequest {
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = "api.music.apple.com"
urlComponents.path = "/v1/me/library/playlists/
// Create and configure the `URLRequest`.
var urlRequest = URLRequest(url: urlComponents.url!)
urlRequest.httpMethod = "GET"
urlRequest.addValue("Bearer \(developerToken)", forHTTPHeaderField: "Authorization")
urlRequest.addValue(userToken, forHTTPHeaderField: "Music-User-Token")
return urlRequest
}
func addPlaylistPathURLString(with developertoken: String, userToken: String, completion: @escaping CatalogSearchCompletionHandler) {
guard let developerToken = refreshDeveloperToken() // its developer token
else {
fatalError("Developer Token not configured. See README for more details.")
}
let urlRequest = AppleMusicRequestFactory.addPlaylistPathURLString(developerToken: developerToken, userToken: userToken)
print(urlRequest)
let task = urlSession.dataTask(with: urlRequest) { (data, response, error) in
guard error == nil, let urlResponse = response as? HTTPURLResponse, urlResponse.statusCode == 200 else {
completion([], error)
return
}
guard
let data = data,
let json = String(data: data, encoding: .utf8)
else { return }
print("json:", json)
do {
// do your stuffs---
} catch {
print("An error occurred: \(error.localizedDescription)")
}
}
task.resume()
}
关于如何从开发者令牌中获取用户令牌,
func requestUserToken() {
guard let developerToken = appleMusicManager.refreshDeveloperToken() // its developer token
else {
return
}
if SKCloudServiceController.authorizationStatus() == .authorized {
let completionHandler: (String?, Error?) -> Void = { [weak self] (token, error) in
guard error == nil else {
print("An error occurred when requesting user token: \(error!.localizedDescription)")
return
}
guard let token = token else {
print("Unexpected value from SKCloudServiceController for user token.")
return
}
self?.userToken = token
print(token)
/// Store the Music User Token for future use in your application.
let userDefaults = UserDefaults.standard
userDefaults.set(token, forKey: AuthorizationManager.userTokenUserDefaultsKey)
userDefaults.synchronize()
if self?.cloudServiceStorefrontCountryCode == "" {
self?.requestStorefrontCountryCode()
}
NotificationCenter.default.post(name: AuthorizationManager.cloudServiceDidUpdateNotification, object: nil)
}
if #available(iOS 11.0, *) {
cloudServiceController.requestUserToken(forDeveloperToken: developerToken, completionHandler: completionHandler)
} else {
cloudServiceController.requestPersonalizationToken(forClientToken: developerToken, withCompletionHandler: completionHandler)
}
}
}