今天。。。功能和工作原理!
我想将yelp api合并到一个应用程序中,但无法在URL字符串上成功传递我的授权令牌。我需要做些什么来将URLRequest连接到URLSessoin调用并且它不使用头吗?也许键值对不对?以下函数返回:
error = {
code = "TOKEN_MISSING";
description = "An access token must be supplied in order to use this endpoint.";
};
我可以使用postman来让yelp API调用正常工作,但只需单击postman上的“Header”部分,输入Bearer,然后输入yelp密钥。我在google上搜索了一下,发现了一些链接,这些链接表明您可以向URLSession添加一个头,我认为它可以像postman那样工作,但我还无法让它工作。
我知道有些GitHub有yelp API回购协议,但我试图不在我的应用程序中安装大量我不理解的代码,因为我只想看到postman上的JSON。有谁能帮助我理解我将如何编辑类似于下面这个例子的代码,这样我就可以得到yelp需要的授权/承载?
func getYelp() {
let appSecret = "Bearer <YELP APIKEY>"
let link = "https://api.yelp.com/v3/businesses/search?latitude=37.786882&longitude=-122.399972"
if let url = URL(string: link) {
// Set headers
var request = URLRequest(url: url)
request.setValue("Accept-Language", forHTTPHeaderField: "en-us")
request.setValue(appSecret, forHTTPHeaderField: "Authorization")
print("Attempting to get places around location from Yelp")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
} else {
if let urlContent = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject // Added "as anyObject" to fix syntax error in Xcode 8 Beta 6
print("Printing all JSON/n/n//n--------------------------")
print(jsonResult)
print("Printing from results/n/n//n--------------------------")
if let description = ((jsonResult["search"] as? NSDictionary)?["context"] as? NSDictionary)?["href"] as? String {
} else {
print("JSON pull failed/n/n//n--------------------------")
}
} catch {
print("JSON Processing Failed/n/n//n--------------------------")
}
}
}
}
task.resume()
} else {
resultLabel.text = "Couldn't get results from Here"
}
}
最佳答案
您在标题和URL之间混合,需要正确设置页眉。
if let url = URL(string: "https://places.cit.api.here.com/places/v1/discover/around?at=37.776169%2C-122.421267&app_id=\(app_id)&app_code=\(app_code)") {
var request = URLRequest(url: url)
// Set headers
request.setValue("Accept-Language", forHTTPHeaderField: "en-us")
request.setValue("Authorization", forHTTPHeaderField: "Bearer " + token // Token here)
print("Attempting to get places around location")
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
// ...
关于ios - 如何传递承载 token 以使用URLSessoin进行Yelp API调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52799277/