Expected to connect to ContentView which is my View module with the code below. What can I get rid of, add, or
edit?
import Foundation import SwiftUI
struct ContentView: View { @State private var searchQuery = "" @State private var searchResult: SearchResult?
var body: some View {
VStack {
UITextField
.padding()
.background(Color.gray.opacity(0.2))
.cornerRadius(10)
.padding()
Button(action: {
Task {
do {
let resultData = try await queryAPI(for: searchQuery)
searchResult = try JSONDecoder().decode(SearchResult.self, from: resultData)
} catch {
print("Error: \(error)")
}
}
}) {
Text("Search")
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(10)
}
if let result = searchResult {
Text(result.answer)
.padding()
}
}
}
func queryAPI(for query: String) async throws -> Data {
let url = URL(string: "https://example.com/search?q=\(query)")!
let (data, _) = try await URLSession.shared.data(from: url)
return data
}
}
struct SearchResult: Codable { let query: String let answer: String }