gpt4 book ai didi

Trying to translate a curl API request into Swift(尝试将cURL API请求转换为SWIFT)

转载 作者:bug小助手 更新时间:2023-10-25 09:25:53 26 4
gpt4 key购买 nike



I am trying to take a curl request I have for an AWS lambda function and write Swift code to call it for my iOS app.

我正在尝试接受我对AWS lambda函数的cURL请求,并编写SWIFT代码在我的iOS应用程序中调用它。



curl -X GET -H "x-api-key: key" -H "Content-Type: application/json" "https://gvt5bk3.execute-api.us-east-2.amazonaws.com/default/functionName?mode=0&query_since=5"



That is the curl request (URL and API key are fake).

这就是cURL请求(URL和API密钥是假的)。


This is my Swift code. When I run it, it says it decodes to {message:forbidden}. When I run the curl in the terminal it works, but my Swift code does not. How do I fix this?

这是我的SWIFT密码。当我运行它时,它会说它会解码为{Message:Forbited}。当我在终端中运行Curl时,它可以工作,但我的SWIFT代码不能。我该怎么解决这个问题?


var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue(apiKey, forHTTPHeaderField: "x-api-key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("Error: \(error)")
} else if let data = data {
let decoder = JSONDecoder()
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
// Now you have a dictionary representing the JSON data
print("Decoded JSON: \(json)")
}
let postData = try decoder.decode(PostsResponse.self, from: data)
DispatchQueue.main.async {
self.updatePosts(postData: postData)
}
} catch {
print("Failed to decode: \(error)")
}
}
}
task.resume()

更多回答

Typo: You are ignoring the request dataTask(with: request)

拼写错误:您忽略了请求数据任务(With:Request.)

This fixed my issue, thanks!

这解决了我的问题,谢谢!

优秀答案推荐

Longer answer:

更长的答案:


There are several ways to create a data task, including these two methods:

创建数据任务有多种方法,包括以下两种方法:


URLSession.dataTask(with: URL)

and


URLSession.dataTask(with: URLRequest)

Since you want to provide an API key, you should be using URLSession.dataTask(with: URLRequest). You're calling URLSession.dataTask(with: URL) by mistake, and so not providing an API key.

因为您想提供一个API密钥,所以您应该使用URLSession.dataTask(带有:URLRequest)。您错误地调用了URLSession.dataTask(with:url),因此没有提供API密钥。


(Vadian already provided this info in a comment, but I thought I'd explain why the incorrect code compiled.

(Vadian已经在评论中提供了这一信息,但我想我应该解释一下为什么编译了不正确的代码。


更多回答

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