gpt4 book ai didi

ios - 如何传递不记名 token 以使用 URLSession 进行 Yelp API 调用

转载 作者:行者123 更新时间:2023-11-28 11:44:54 28 4
gpt4 key购买 nike

U P D A T E D... 有效的功能!我想将 yelp api 合并到应用程序中,但无法在 URL 字符串上成功传递我的授权 token 。我需要做些什么来将 URLRequest 连接到 URLSessoin 调用并且它不使用 header 吗?也许键值对是错误的?下面的函数返回:

error =     {
code = "TOKEN_MISSING";
description = "An access token must be supplied in order to use this endpoint.";
};

我能够使用 postman 使 yelp API 调用正常工作,但只能通过单击 postman 上的“Header”部分并输入 Bearer,然后输入我的 yelp 键。我用谷歌搜索了一下,发现一些链接表明您可以向 URLSession 添加 header ,我认为它可以像 postman 那样工作,但我无法让它工作。

我知道有一些带有 yelp API 存储库的 github,但我试图不在我的应用程序中安装大量我不理解的代码,而我想要的只是我可以看到的 JSON 正在通过 postman 。任何人都可以帮助我理解我将如何编辑类似于下面的 Here 示例的代码,以便我可以获得 yel​​p 所需的授权/Bearer?

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"
}
}

最佳答案

您混淆了 header 和 url,您需要正确设置 header

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 以使用 URLSession 进行 Yelp API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52799277/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com