Search code examples
swiftnsurlsessionurlsession

Swift Parse Google Search API Text File


I am trying to parse the results from Google's search autocomplete endpoint at http://suggestqueries.google.com/complete/search?client=firefox&q=YOURQUERY, but it's returning a textfile without keys.

This is an example output:

["YOURQUERY",["yourquery","yourquery dou","yourquery s.r.o","yourquery отзывы","yourquery львів","yourquery s.r.o. львів"]]

This is my code:

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

I'm getting an decoding error:

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

How would you decode this correctly?


Solution

  • Your problem there is that the JSON returned is an array of Any. The first element is a String and the second is an array of strings [String]. Since Any does not conform to Decodable it would be easier to use JSONSerialization method

    class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
    

    to cast the result from Any to [Any] and cast the last element to an array of strings [String].


    let results = try (JSONSerialization.jsonObject(with: data) as? [Any])?.last as? [String] ?? []
    print(results)
    

    This will print

    "["yourquery", "yourquery dou", "yourquery s.r.o", "yourquery отзывы", "yourquery львів", "yourquery s.r.o. львів"]\n"