Home > Uncategorized > #Bing Image Search using Swift

#Bing Image Search using Swift

swift-1

Here’s a quick code snippet on how to use Microsoft’s Bing Search API (AKA Cognitive image API) with Swift and the AlamoFire Cocoapod. You’ll need to get a API key for the bing image search API, and replace the \(Secret.subscriptionKey) below.

static func Search(keyword : String, completion: @escaping (UIImage, String) -> Void )

    {

        let escapedString = keyword.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

        let strUrl = https://api.cognitive.microsoft.com/bing/v7.0/images/search?q=\(escapedString)&count=1&subscription-key=\(Secret.subscriptionKey)”

        Alamofire.request(strUrl).responseJSON { (response) in

             if response.result.isSuccess {

                let searchResult : JSON = JSON (response.result.value!)

                // To-Do: handle image not found

                let imageResult = searchResult[“value”][0][“contentUrl”].string!

                print(imageResult)

                Alamofire.request(imageResult).responseData(completionHandler: { (response) in

                    if response.result.isSuccess {

                        let image = UIImage(data: response.result.value!)

                        completion(image!, imageResult)

                    }

                    else

                    {

                        print(“Image Load Failed! \(response.result.error ?? “error” as! Error)”)

                    }

                })

            }

            else{

                print(“Bing Search Failed! \(response.result.error ?? “error” as! Error)”)

            }

        }

    }

It’s called like so:

Search(keyword: “Kittens”){ (image,url) in

imageView.image = image

}

Advertisements
Categories: Uncategorized
  1. April 22, 2018 at 6:35 pm

    Oh, and you need the SwiftyJSON cocaopod too ! 🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: