我正在尝试使用此示例代码(https://github.com/hirayaCM/AppleMusicSearch)向 Apple Music API 发送请求。我只是将开发人员令牌替换为我的并运行它。
但是,即使我创建和使用新的开发人员令牌,我总是会收到 401 错误。我使用 curl 检查我的开发人员令牌是否正确,并且 curl 的请求成功。
谁能告诉我出了什么问题?
这是示例代码的 APIClient 部分。
func search(term: String, completion: @escaping (SearchResult?) -> Swift.Void) {
let completionOnMain: (SearchResult?) -> Void = { searchResult in
DispatchQueue.main.async {
completion(searchResult)
}
}
guard var components = URLComponents(string: "https://api.music.apple.com/v1/catalog/\(APIClient.countryCode)/search") else { return }
let expectedTerms = term.replacingOccurrences(of: " ", with: "+")
let urlParameters = ["term": expectedTerms,
"limit": "10",
"types": "albums"]
var queryItems = [URLQueryItem]()
for (key, value) in urlParameters {
queryItems.append(URLQueryItem(name: key, value: value))
}
components.queryItems = queryItems
var request = URLRequest(url: components.url!)
request.httpMethod = "GET"
request.addValue("Bearer \(APIClient.developerToken)",
forHTTPHeaderField: "Authorization")
data(with: request) { data, error -> Void in
guard error == nil else {
print(#function, "URL Session Task Failed", error!)
completionOnMain(nil)
return
}
guard let searchResult = try? JSONDecoder().decode(SearchResult.self, from: data!) else {
print(#function, "JSON Decode Failed");
completionOnMain(nil)
return
}
completionOnMain(searchResult)
}
}
func album(id: String, completion: @escaping (Resource?) -> Swift.Void) {
let completionOnMain: (Resource?) -> Void = { resource in
DispatchQueue.main.async {
completion(resource)
}
}
guard let url = URL(string: "https://api.music.apple.com/v1/catalog/\(APIClient.countryCode)/albums/\(id)") else { return }
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("Bearer \(APIClient.developerToken)",
forHTTPHeaderField: "Authorization")
data(with: request) { data, error -> Void in
guard error == nil else {
print(#function, "URL Session Task Failed", error!)
completionOnMain(nil)
return
}
guard let jsonData = try? JSONSerialization.jsonObject(with: data!),
let dictionary = jsonData as? [String: Any],
let dataArray = dictionary["data"] as? [[String: Any]],
let albumDictionary = dataArray.first,
let albumData = try? JSONSerialization.data(withJSONObject: albumDictionary),
let album = try? JSONDecoder().decode(Resource.self, from: albumData) else {
print(#function, "JSON Decode Failed");
completionOnMain(nil)
return
}
completionOnMain(album)
}
}
谢谢。