Swift Api密钥认证

Xap*_*phy 0 api swift

我正在尝试使用Zomato的API获取JSON数据的简单get请求.我有一个API密钥,但我不知道如何在我的正常NSURLSession调用中使用它.我没有提供用户名或密码,只提供32个字符的API密钥.

curl命令如下:

curl -X GET --header "Accept: application/json" --header "user_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "https://developers.zomato.com/api/v2.1/search?entity_id=280&entity_type=city&count=5&cuisines=55"
Run Code Online (Sandbox Code Playgroud)

我的请求代码在这里:

        let url = NSURL(string: myURL)!
        let urlSession = NSURLSession.sharedSession()
        //add api key to header somewhere here?

        let myQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in

            //I have some error handling here


                var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary
                let myArray:NSArray = jsonResult["restaurants"] as! NSArray
        })
        myQuery.resume()
Run Code Online (Sandbox Code Playgroud)

jam*_*esk 6

该文档的NSURLSession.sharedSession()说:

换句话说,如果你正在做什么用的高速缓存,饼干,认证,或自定义的网络协议,你或许应该使用的,而不是共享会话的自定义会话.

您可以创建自己的自定义会话并包含标题,如下所示:

let url = NSURL(string: myURL)!

let config = NSURLSessionConfiguration.defaultSessionConfiguration()

config.HTTPAdditionalHeaders = [
    "Accept": "application/json",
    "user_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
]

let urlSession = NSURLSession(configuration: config)

let myQuery = urlSession.dataTaskWithURL(url, completionHandler: {
    data, response, error -> Void in
    /* ... */
})
myQuery.resume()
Run Code Online (Sandbox Code Playgroud)