Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift Api密钥认证_Swift_Api - Fatal编程技术网

Swift Api密钥认证

Swift Api密钥认证,swift,api,Swift,Api,我试图提出一个简单的get请求,使用Zomato的API获取JSON数据。我有一个API密钥,但我不确定如何在正常的NSURLSession调用中使用它。我没有提供用户名或密码,只有一个32字符的API密钥 curl命令如下所示: curl -X GET --header "Accept: application/json" --header "user_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "https://developers.zomato.com/api/

我试图提出一个简单的get请求,使用Zomato的API获取JSON数据。我有一个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"
我的申请代码如下:

        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()
NSURLSession.sharedSession()的

换句话说,如果您正在使用缓存、cookie、身份验证或自定义网络协议进行任何操作,那么您可能应该使用自定义会话而不是共享会话

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

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()
NSURLSession.sharedSession()的

换句话说,如果您正在使用缓存、cookie、身份验证或自定义网络协议进行任何操作,那么您可能应该使用自定义会话而不是共享会话

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

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()

谢谢,回答了我的问题。谢谢,回答了我的问题。