2015-11-28 133 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