如何使用 SwiftUI 显示解析的数据? [英] How to show parsed data with SwiftUI?
问题描述
我正在尝试使用 SwiftUI 在视图中显示从 API 解析的数据.
I'm trying to show in a view parsed data from an API using SwiftUI.
我正在使用此代码正确获取数据:
I'm fetching correctly the data using this code:
import UIKit
class APIController: ObservableObject {
func apiCall() {
// URL
let url = URL(string: "https://geek-jokes.p.rapidapi.com/api?format=json")
guard url != nil else {
print("Error creating url object")
return
}
// URL Rquest
var request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
// Specify the header
let headers = [
"x-rapidapi-key": "d1363cbe66msh266920b6366eaacp1f87dfjsn050e3f8e58e2",
"x-rapidapi-host": "geek-jokes.p.rapidapi.com"
]
request.allHTTPHeaderFields = headers
// Specify the body
// let jsonObject = [
// "sign": "Aries"
// ] as [String:Any]
//
// do {
// let requestBody = try JSONSerialization.data(withJSONObject: jsonObject, options: .fragmentsAllowed)
//
// request.httpBody = requestBody
// }
// catch {
// print("Error creating the data object from json")
// }
// Set the request type
request.httpMethod = "GET"
// Get the URLSession
let session = URLSession.shared
// Create the data task
let dataTask = session.dataTask(with: request) { data, response, error in
// Check for errors
if error == nil && data != nil {
// Try to parse out the JSON data
let decoder = JSONDecoder()
do {
let jokesData = try decoder.decode(JokesData.self, from: data!)
print(jokesData)
}
catch {
print("Error in JSON parsing")
}
// Try to print out the JSON data
// do {
// let dictionary = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String:Any]
// print(dictionary)
//
// }
// catch {
// print("Error parsing response data")
// }
}
}
// Fire off the data task
dataTask.resume()
}
}
然后我不确定是否在 JokesData.swift 中正确导入了数据
Then I'm not sure if the data is correctly imported in JokesData.swift
import foundation
struct JokesData: Codable {
var joke:String = ""
}
当我尝试在 JokesView.swift 中加载数据时,什么也没有出现:(
And when I try to load the data in JokesView.swift, nothing appear :(
import SwiftUI
struct JokesView: View {
var jokesData: JokesData
@StateObject var viewRouter: ViewRouter
var body: some View {
Text(jokesData.joke)
.foregroundColor(.black)
}
}
如果有人知道我做错了什么,那将非常有帮助.
If someone has an idea of what I did wrong, it would be very helpful.
推荐答案
在
APIController
中添加一个属性@Published var jokesData = JokesData()
用
Replace the
do - catch
block in the completion handler withdo { let jokesData = try decoder.decode(JokesData.self, from: data!) print(jokesData) DispatchQueue.main.async { self.jokesData = jokesData } } catch { print(error) }
它将接收到的数据分配给发布的
jokesData
属性.it assigns the received data to the publishing
jokesData
property.在视图中创建控制器的
@StateObject
,在onAppear
修饰符中加载数据,视图会自动更新.In the view create a
@StateObject
of the controller, in theonAppear
modifier load the data, the view will be updated automatically.import SwiftUI struct JokesView: View { @StateObject var apiController = APIController() var body: some View { Text(apiController.jokesData.joke) .foregroundColor(.black) .onAppear() { apiController.apiCall() } } }
这篇关于如何使用 SwiftUI 显示解析的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!