I m working on a feature that involves sending a JSON request and then receiving a JSON response. However, I m facing an issue while trying to display the received JSON data on a subsequent view, specifically the JSONResponseView
.
The problem I m encountering is that when I navigate to the JSONResponseView
, I m only seeing an empty JSON object displayed there [:]
. This is perplexing to me because I can confirm from the console logs that I am indeed receiving a valid JSON response.
为了给你一个更细微的背景,我已经开展了一个进程,由我提出初专干事的请求,接受初专干事的答复,然后试图提出< 条码>。 查阅数据代码>。 然而,尽管我收到答复后触发了JSONResponseView陈述,但这种观点似乎显示一个空洞的JSON物体。
是否有可能推迟接收JSON的答复。 我已核实,我何时触发“JSONResponseView”和何时作出回复的时机几乎是瞬时的,已降至2毫米。
我为什么会遇到这种行为? 我如何妥善通过并显示在<代码>JSONResponse上收到的JSON数据。 观点:
var body: some View {
Form {
PersonDetailsSection(name: $person1Name, title: "Enter Person 1 s Details")
Button {
if let jsonData = JSONPayloadGenerator.createPayload(person1Name: person1Name) {
sendRequest(with: jsonData)
}
}
}
.navigationBarTitle("My App")
.padding()
.sheet(isPresented: $showingResponseView) {
JSONResponseView(jsonResponse: responseJSON)
.onAppear {
print("Presenting JSONResponseView")
}
}
func sendRequest(with jsonData: Data) {
// Create the URL
guard let url = URL(string: "http://localhost:7071/api") else {
print("Invalid URL")
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
// Make the request
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error:", error)
return
}
guard let data = data else {
print("No data received")
return
}
// Print the raw JSON data received from the server
if let jsonString = String(data: data, encoding: .utf8) {
print("-->Raw JSON Data Received:", jsonString)
}
do {
let result = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
print(" Report:", result ?? "No result")
// Update the responseJSON state with the received JSON data
responseJSON = result ?? ["Test": "OK"]
// Present the JSONResponseView
showingResponseView = true
} catch {
print("Error parsing JSON:", error)
}
}
task.resume()
// Print the JSON payload
if let jsonString = String(data: jsonData, encoding: .utf8) {
print("Generated JSON Payload Outgoing:
", jsonString)
}
}
}