#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!
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
}
Oh, and you need the SwiftyJSON cocaopod too ! 🙂
LikeLike