gpt4 book ai didi

iOS swift - 处理来自 API 的响应

转载 作者:搜寻专家 更新时间:2023-11-01 06:55:52 26 4
gpt4 key购买 nike

我对 Swift 和 iOS 开发还很陌生。我想知道如果我使用 JavaScript,如何做一些相对简单的事情。

我正在调用返回以下内容的 API。请原谅格式化,但它是直接从 Xcode 控制台复制的。

["type": success, "value": <__NSArrayI 0x600000030340>(
{
categories = ();
id = 155;
joke = "Chuck Norris does not &quot;style&quot; his hair. It lays perfectly in place out of sheer terror.";
},
{
categories = (nerdy);
id = 69;
joke = "Scientists have estimated that the energy given off during the Big Bang is roughly equal to 1CNRhK (Chuck Norris Roundhouse Kick).";
}
)
]

我想遍历响应并添加到数组中。在 JavaScript 中,它看起来像下面这样:

let jokes = [];
response.value.forEach(item => {
jokes.push(item.joke)
})

不一定要和上面的完全一样。我有信心快速使用循环并附加到数组。我正在努力做的是访问从 API 返回的 value 数组中的笑话。

我的 Controller 如下所示:

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
} catch let error as NSError {
print(error)
}
}).resume()
}
}

最佳答案

你可以试试

if let va = json["value"] as? [[String:Any]] {
va.forEach { print($0["joke"]) }
}

我更愿意为此编写一个Codable结构

struct Root: Codable {
let type: String
let value: [Value]
}

struct Value: Codable {
let categories: [Category]
let id: Int
let joke: String
}

struct Category: Codable {
}

let res = try? JSONDecoder().decode(Root.self,from:data)
print(res.value)

关于iOS swift - 处理来自 API 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53432664/

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