LoginSignup
24
19

More than 5 years have passed since last update.

Swift4の機能を活用してGoogle画像検索結果を利用する

Last updated at Posted at 2017-10-09

Google画像検索APIをiOSで利用する - Qiita
https://qiita.com/ukandori/items/234156f97eb6dad77966
などの先人を参考に。Codableや新しいreduceURLComponentsを使ったらだいぶシンプルになりました。
(追記)コメントを受けて、URLComponentsに書き替えました。こちらのほうがStringでやるより適切ですね。

// Structure defined by https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response
struct CustomSearchedResult: Codable {
    struct Item: Codable {
        struct Image: Codable {
            let contextLink: String
            let thumbnailLink: String
            let thumbnailHeight: Int
            let thumbnailWidth: Int
        }
        let link: URL
        let displayLink: URL
        let mime: String
        let image: Image
    }
    let items: [Item]
}

let query = "ほげほげ"
var urlComponents = URLComponents(string: "https://www.googleapis.com/customsearch/v1")!
urlComponents.queryItems = [
    URLQueryItem(name: "searchType", value: "image"),
    URLQueryItem(name: "q", value: query),
    // To get `key`, create your own project from https://console.developers.google.com/projectcreate
    URLQueryItem(name: "key", value: "xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"), 
    // To get `cx`, create your own search engine from https://cse.google.com/cse/create/new
    URLQueryItem(name: "cx", value: "000000000000000000000:xxxxxxxxxxx")
]
print(urlComponents.string!)

let task = URLSession.shared.dataTask(with: urlComponents.url!) { data, response, error in
    guard let jsonData = data else {
        print(error as Any)
        return
    }

    do {
        let result = try JSONDecoder().decode(CustomSearchedResult.self, from: jsonData)
        print(result.items[0])

        let task = URLSession.shared.dataTask(with: result.items[0].link) {data, response, error in
            guard let image = data.flatMap(UIImage.init) else {
                print(error as Any)
                return
            }
            // imageとれた
        }
        task.resume()
    } catch(let e) {
        print(e)
    }
}
task.resume()
24
19
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
19