Spotify Поиск по каталогу запрос: 400 Неправильный запрос - PullRequest
0 голосов
/ 15 сентября 2018

Я пытаюсь реализовать запрос каталога поиска с помощью веб-интерфейса spotify. Я следовал http-формату запроса согласно документации API, но я получаю ответ Bad Request 400. Вот мой код Кто-нибудь может указать, что здесь не так?

Функция создания запроса:

static func createSpotifySearchRequest(with term: String, developerToken: String) -> URLRequest {

    // Create the URL components for the network call.
    var urlComponents = URLComponents()
    urlComponents.scheme = "https"
    urlComponents.host = "api.spotify.com"
    urlComponents.path = "/v1/search"
    print(urlComponents.host)
    let expectedTerms = term.replacingOccurrences(of: " ", with: "+")
    let urlParameters = ["offset": "5",
                         "limit": "10",
                         "market": "United+States",
                         "type": "track",
                         "q": expectedTerms]

    urlComponents.queryItems = [URLQueryItem(name: "q", value: "Hotel+California"), URLQueryItem(name: "type", value: "track"), URLQueryItem(name: "market", value: "United+States"), URLQueryItem(name: "limit", value: "10"), URLQueryItem(name: "offset", value: "5")]


    // Create and configure the `URLRequest`.
    print("in creation spotify")
    var urlRequest = URLRequest(url: urlComponents.url!)
    urlRequest.httpMethod = "GET"
    print(urlRequest)
    urlRequest.addValue("Bearer \(developerToken)", forHTTPHeaderField: "Authorization")

    print(urlRequest)
    print (urlRequest.allHTTPHeaderFields)
    print("exiting creation spotify")
    return urlRequest
}

Вызов функции:

let developerToken = (self.userDefaults.object(forKey: "Spotify_access_token")) as! String

    let urlRequest = createSpotifySearchRequest(with: term, developerToken: developerToken)

    //print(urlRequest)
    //print (developerToken)
    let task = urlSession.dataTask(with: urlRequest) { (data, response, error) in
        //print(error)
        print(response)
        guard error == nil, let urlResponse = response as? HTTPURLResponse, urlResponse.statusCode == 200 else {
            completion([], error)
            //print("error response")
            //print(error)
            return
        }
        //print(urlResponse)
        //print("response should be above this guy")
        do {
            let spotifyMediaItems = try self.processSpotifyMediaItemSections(from: data!)
            completion(spotifyMediaItems, nil)
            print(spotifyMediaItems)

        } catch {
            fatalError("An error occurred: \(error.localizedDescription)")
        }
    }

    task.resume()

Журналы отладки:

in creation spotify
https://api.spotify.com/v1/search?q=Hotel+California&type=track&market=United+States&limit=10&offset=5
https://api.spotify.com/v1/search?q=Hotel+California&type=track&market=United+States&limit=10&offset=5
Optional(["Authorization": "Bearer BQC4ZpVXj97*****************Y77yHzYR6HnxnxAiOPwVLA"])
exiting creation spotify
Optional(<NSHTTPURLResponse: 0x106a55f70> { URL: https://api.spotify.com/v1/search?q=Hotel+California&type=track&market=United+States&limit=10&offset=5 } { Status Code: 400, Headers {
"Access-Control-Allow-Origin" =     (
    "*"
);
"Cache-Control" =     (
    "private, max-age=0"
);
"Content-Encoding" =     (
    gzip
);
"Content-Length" =     (
    93
);
"Content-Type" =     (
    "application/json; charset=utf-8"
);
Date =     (
    "Fri, 14 Sep 2018 22:18:31 GMT"
);
Via =     (
    "1.1 google"
);
"access-control-allow-credentials" =     (
    true
);
"access-control-allow-headers" =     (
    "Accept, Authorization, Origin, Content-Type, Retry-After"
);
"access-control-allow-methods" =     (
    "GET, POST, OPTIONS, PUT, DELETE, PATCH"
);
"access-control-max-age" =     (
    604800
);
"alt-svc" =     (
    clear
);
} })

1 Ответ

0 голосов
/ 15 сентября 2018

Ваш URL Params имеет "market" = "United States", это недопустимый рынок, вы должны использовать "US" для этого значения. Я проверил это, и message, возвращаемое в error, говорит «Неверный код рынка»

...