gpt4 book ai didi

ios - 带有身份验证的 API Swift 4 调用。简单的。但卡住了

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

找到一个简单的答案让我终于问了。

我需要做什么/添加什么来发送带有 url 调用的身份验证?我全力以赴,但就是看不到解决方案。

使用必要的信息设置 url,然后调用电话。这是 Curl 调用:

curl -v -X GET https://api.jsecoin.com/v1.7/balance/auth/0/ \
-H "Content-Type: application/json" \
-H "Authorization: JSE API Key"

示例响应:

{
"success": 1,
"notification": "Your balance is 99 JSE",
"balance": 99
}

这是我在 Swift 4、XCode 9.xx iOS 11.4 中执行此操作的代码片段,但我不知道如何添加授权。

 func makeGetCall() {
// Set up the URL request
//let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"


let todoEndpoint: String = "https://api.jsecoin.com/v1.7/balance/auth/0/"

//-H \"Content-Type: application/json\" -H \"Authorization: xxxxxxxxxxxxxxxxx\""

guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)

// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)

config.httpAdditionalHeaders = [
"Content-Type": "application/json",
"Authorization": "xxxxxxxxxxxxxxxxxxxxx"
]

// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /todos/1")
print(error!)
return
}

返回,

The todo is: ["notification": API Balance Failed: User API key credentials  could not be matched, "fail": 1]

无法从 JSON 获取待办事项标题

最佳答案

您需要在 URLRequest 中设置 Header 参数,而不是在 URLSessionConfiguration 中

这是你的解决方案

func makeGetCall() {
// Set up the URL request
//let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"


let todoEndpoint: String = "https://api.jsecoin.com/v1.7/balance/auth/0/"

//-H \"Content-Type: application/json\" -H \"Authorization: xxxxxxxxxxxxxxxxx\""

guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)


urlRequest.setValue(signature, forHTTPHeaderField: "Authorization")
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)



// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /todos/1")
print(error!)
return
}

关于ios - 带有身份验证的 API Swift 4 调用。简单的。但卡住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51379707/

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