我的代碼:
import SwiftUI
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
var author: String
var text: String
}
struct ContentView: View {
@State private var results = [Result]()
var body: some View {
List(results, id: \.author) { item in // <--- This is where the problem is
VStack(alignment: .leading) {
Text(item.text)
Text(item.author)
}
}
.task{
await loadData()
}
}
func loadData() async{
guard let url = URL(string: "https://type.fit/api/quotes") else {
print("Invalid URL")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
results = decodedResponse.results
print(results)
}
} catch {
print("Invalid data")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
教程視頻:https ://www.youtube.com/watch?v=MBCX1atOvdA&t=13s
問題是我正在關注的教程呼叫了不同的 api,并在串列中顯示結果時使用了我的 api 未提供的資訊作為 id。本教程使用 api 提供的整數作為將資料放入串列格式時的索引。我只是不確定我應該為我的 id 使用什么,或者是否有更好的方法可以讓資訊顯示在串列中
我使用的 api 資料格式為 & 可以在https://type.fit/api/quotes參考:
[
{
"text": "Genius is one percent inspiration and ninety-nine percent perspiration.",
"author": "Thomas Edison"
},
{
"text": "text",
"author": "author"
}, //and continues on for about 75,000 quotes
]
我試圖設定 id: .author 和 id: .text 兩者都沒有拋出錯誤,但是當我運行構建時我什么也沒得到
我想只得到一組可以顯示給用戶的“文本”和“作者”資訊
我沒有嘗試太多,因為我對 swiftui 和 xcode 還比較陌生。我覺得這應該是一個簡單的修復,我可能只是很難用我的谷歌搜索來找到解決方案。
如前所述,我想最終顯示一對包含 1 個“文本”和 1 個“作者”的結果
uj5u.com熱心網友回復:
要從服務器獲取資料,您需要將模型結構與 json 資料相匹配。在您的情況下,json 資料是一個引號陣列。因此,鑒于 theauthor
和可能的text
, 可能為空,因此您需要對此進行解碼。
試試這個示例代碼,對我來說效果很好:
// -- here
struct Quote: Identifiable, Codable {
let id = UUID() // <-- ensures a unique id
var author: String?
var text: String?
enum CodingKeys: String, CodingKey {
case author, text // <-- id is missing, it will not be decoded
}
}
struct ContentView: View {
@State var quotes = [Quote]() // <-- here
var body: some View {
VStack {
if quotes.count > 0 {
Text(quotes[0].text ?? "no text") // <-- here
Text(quotes[0].author ?? "no author").foregroundColor(.blue) // <-- here
}
}
// List(quotes) { quote in
// VStack(alignment: .leading) {
// Text(quote.text ?? "no text") // <-- here
// Text(quote.author ?? "no author").foregroundColor(.blue) // <-- here
// }
// }
.task{
await loadData()
}
}
func loadData() async {
guard let url = URL(string: "https://type.fit/api/quotes") else {
print("Invalid URL")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
quotes = try JSONDecoder().decode([Quote].self, from: data) // <-- here
} catch {
print(error) // <-- important
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/531081.html
標籤:迅速代码迅捷swiftui 列表
上一篇:傳遞給呼叫的引數在Webview的swift上不帶任何引數
下一篇:如何分離兩個顏色值