1

I am trying to send a request to Apple Music API by using this sample code (https://github.com/hirayaCM/AppleMusicSearch). I just replaced developer token to mine and run it.

However I am always getting 401 error even if I create and use new developer token. I used curl to check if my developer token is correct or not and request by curl was succeed.

Can anyone tell me what is wrong?

Here's the APIClient part of the sample code.

    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)
    }
}

Thanks.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

0 Answers0