2015-11-28 35 views
0

我正在尝试使用Zomato的API来获取JSON数据的简单获取请求。我有一个API密钥,但我不知道如何在正常的NSURLSession调用中使用它。我没有提供用户名或密码,只有一个32位字符的API密钥。Swift 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() 

回答

3

documentationNSURLSession.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() 
+0

谢谢,回答我的问题。 – PTerz