Я пытаюсь проанализировать результаты с конечной точки автозаполнения поиска Google на http://suggestqueries.google.com/complete/search?client=firefox&q=YOURQUERY, но возвращается текстовый файл без ключей.
Это пример выходных данных:
["YOURQUERY",["yourquery","yourquery dou","yourquery s.r.o","yourquery отзывы","yourquery львів","yourquery s.r.o. львів"]]
Это мой код:
let baseURL = "http://suggestqueries.google.com/complete/search?client=firefox&q="
var searchResults: [String] = []
func returnResults(searchTerm: String, completion: @escaping ([String?], Error?) -> Void) {
let finalUrl = URL(string: baseURL + searchTerm)
// 3. choose method to transmit and configure to do so
var request = URLRequest(url: finalUrl!)
request.httpMethod = "GET"
// 4. request data
URLSession.shared.dataTask(with: request) { (data, _, error) in
// check for errors and data
if let error = error {
print("There was an error requesting data")
return completion([], error)
}
guard let data = data else {
print("There was an error getting data.", error)
return completion([], NSError())
}
// if we got our data back, we need to decode it to match our model object
let jsonDecoder = JSONDecoder()
do {
// 1. decode results into array
let results = try jsonDecoder.decode([String].self, from: data)
// 2. set search results var equal to our decoded results array
self.searchResults = results
completion(results, nil)
} catch {
print("There was an error decoding data.", error)
completion([], error)
}}.resume()
}
Я получаю ошибку декодирования:
There was an error decoding data. typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1", intValue: 1)], debugDescription: "Expected to decode String but found an array instead.", underlyingError: nil))
Как бы вы расшифровали это правильно?