Swift Api密钥认证

时间:2015-11-28 01:37:06

标签: swift api

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

curl命令如下:

@Override
protected void onResume() {
    super.onResume();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CPUKeepRunning");
    wakeLock.acquire();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (wakeLock != null && wakeLock.isHeld()) {
        wakeLock.release();
        wakeLock = null;
    }
}

我的请求代码在这里:

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"

1 个答案:

答案 0 :(得分:5)

NSURLSession.sharedSession()的{​​{3}}说:

  

换句话说,如果您使用缓存,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()