Swift Api密钥认证
我试图提出一个简单的get请求,使用Zomato的API获取JSON数据。我有一个API密钥,但我不确定如何在正常的NSURLSession调用中使用它。我没有提供用户名或密码,只有一个32字符的API密钥 curl命令如下所示: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/
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()
谢谢,回答了我的问题。谢谢,回答了我的问题。