当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Using bing search API

问题描述:

I'm trying to very simply load data using the Bing api. Here is my code using AlamoFire:

let headers = [

"Ocp-Apim-Subscription-Key": "mykeyishere"

]

request(

.GET,

"https://api.cognitive.microsoft.com/bing/v5.0/search?q=nba&mkt=en-us&safesearch=Moderate",

parameters: headers,

encoding: .URL

).responseJSON { (request, response, json, error) -> Void in

println(error)

println(json)

}

For some reason, I keep getting this error:

Optional({

message = "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API.";

statusCode = 401;

})

网友答案:

parameters are for the parameters, like: q=nba&mkt=en-us&safesearch=Moderate and you need to set headers to use your headers dictionary.

i use Alamofire but it is the same.

    let headers = [
    "Ocp-Apim-Subscription-Key": "laksjgakaask13876tjhgbd"
]

var dic = [String:AnyObject]()

dic["q"] = "NBA" as AnyObject?
dic["mkt"] = "en-us" as AnyObject?
dic["safesearch"] = "Moderate" as AnyObject?

Alamofire.request("https://api.cognitive.microsoft.com/bing/v5.0/images/search", method: .get, parameters: dic, encoding: URLEncoding.default, headers: headers).validate().responseJSON { (response:DataResponse<Any>) in


    switch(response.result) {
    case .success(_):

        if let JSON = response.result.value {

            print(JSON)

            //take URLs from the json into an ImagesURLsArray

        } else {
            print("error with response.result.value")}

    case .failure(_):

        if let errorNum = response.response?.statusCode {
            let stringErrorNum = "{\"error\": \(errorNum)}"
            print(stringErrorNum)

        }

    }

}
  • notice that i'm searching for images (https://api.cognitive.microsoft.com/bing/v5.0/images/search) you were searching for news (https://api.cognitive.microsoft.com/bing/v5.0/search). same thing.
分享给朋友:
您可能感兴趣的文章:
随机阅读: