正在从不同端点下载 JSON 特定数据
downloading JSON for specific data from different endpoint
我正在尝试从不同的端点获取 JSON 图像 urls。目前,我可以调用第一个端点来获取练习名称、描述和 ID 的数据。然后对于每个练习,我都尝试使用 ID 值调用不同的端点,这样我就可以获得特定练习的图像 url。
我唯一的想法是创建对不同端点的嵌套 API 调用,但我遇到了太多的语法错误并且它不起作用。
问题是如何重新格式化我的代码以消除现有的语法错误。
这是我的代码。我从未真正见过执行此类 API 调用的方法。
func parseData() {
fetchedExercise.removeAll()
let url = URL(string: urlPath)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Error while parsing JSON")
}
else {
do {
if let data = data,
let fetchedData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any],
let exercises = fetchedData["results"] as? [[String: Any]] {
for eachExercise in exercises {
if eachExercise["license_author"] as! String == "wger.de" {
let name = eachExercise["name"] as! String
let description = eachExercise["description"] as! String
let id = eachExercise["id"] as! Int
}
它已通过在末尾添加缺失的闭包括号修复,这在尝试 运行 代码时导致语法错误。
我正在尝试从不同的端点获取 JSON 图像 urls。目前,我可以调用第一个端点来获取练习名称、描述和 ID 的数据。然后对于每个练习,我都尝试使用 ID 值调用不同的端点,这样我就可以获得特定练习的图像 url。
我唯一的想法是创建对不同端点的嵌套 API 调用,但我遇到了太多的语法错误并且它不起作用。
问题是如何重新格式化我的代码以消除现有的语法错误。
这是我的代码。我从未真正见过执行此类 API 调用的方法。
func parseData() {
fetchedExercise.removeAll()
let url = URL(string: urlPath)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Error while parsing JSON")
}
else {
do {
if let data = data,
let fetchedData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any],
let exercises = fetchedData["results"] as? [[String: Any]] {
for eachExercise in exercises {
if eachExercise["license_author"] as! String == "wger.de" {
let name = eachExercise["name"] as! String
let description = eachExercise["description"] as! String
let id = eachExercise["id"] as! Int
}
它已通过在末尾添加缺失的闭包括号修复,这在尝试 运行 代码时导致语法错误。