希望对转换后的 api load func 提出一些想法。不知何故,它有效,这是我的第一次尝试。
我问这个问题是因为我想知道 do-catch 中的错误捕获是否涵盖了我删除的所有响应内容。
import SwiftUI
import Foundation
struct ContentView: View {
@State private var food: Food = Food(id: 0, uid: "", dish: "", description: "", ingredient: "", measurement: "")
var body: some View {
display
.lineLimit(10)
.task {
do {
try await getRandomFood()
} catch {
print("Error", error)
}
}
}
// my converted 1st attempt, I wrote this from getRandomFood2() below
func getRandomFood() async throws {
let url = URL(string: "https://random-data-api.com/api/food/random_food")!
do {
let (data, _) = try await URLSession.shared.data(from: url, delegate: nil)
let food = try JSONDecoder().decode(Food.self, from: data)
self.food = food
} catch {
throw error
}
}
// original func do-catch-ified above
func getRandomFood2() async throws {
guard let url = URL(string: "https://random-data-api.com/api/food/random_food") else { fatalError("Missing URL") }
let urlRequest = URLRequest(url: url)
let (data, response) = try await URLSession.shared.data(for: urlRequest)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { fatalError("Error while fetching data") }
let decodedFood = try JSONDecoder().decode(Food.self, from: data)
food = decodedFood
// print("Async decodedFood", decodedFood)
}
var display: some View {
/* ... */
}
}
使用此字符串文字创建 URL 不会失败,可以强制解包。
与其因致命错误而中止代码,不如抛出
URLError
func getRandomFood2() async throws {
let url = URL(string: "https://random-data-api.com/api/food/random_food")!
let (data, response) = try await URLSession.shared.data(from: url)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) }
food = try JSONDecoder().decode(Food.self, from: data)
}
好的,这个网址不能失败。我也这么想。而且 do-catch 是多余的。我现在明白你在说什么了。 所以,我试图让 get..Food2 更加优雅,并提出异步等待要求。
func getRandomFood() async throws {
let url = URL(string: "https://random-data-api.com/api/food/random_food")!
let (data, _ ) = try await URLSession.shared.data(from: url)
food = try JSONDecoder().decode(Food.self, from: data)
}
这似乎工作正常。既然 URL 不能失败,还有什么必要吗?或者这只是在守卫响应线或接球线之间进行选择的问题。 (告诉是否出了什么问题)
这就是所问的。我说我是新人,对我来说没有什么是显而易见的。