Home > Uncategorized > #Bing Image Search using Swift

#Bing Image Search using Swift


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!


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

                    if response.result.isSuccess {

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

                        completion(image!, imageResult)




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





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




It’s called like so:

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

imageView.image = image


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 )

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: