import SwiftUI
struct ContentView: View {
@State private var jsonData: [String: Any] = [:]
var body: some View {
VStack {
Text("JSON Response:")
.font(.headline)
.padding()
Text("\(jsonData)")
.padding()
Button("Fetch JSON") {
fetchDataFromAPI()
}
.padding()
}
}
func fetchDataFromAPI() {
guard let url = URL(string: "https://example.com/api/data") else {
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("Error: \(error)")
return
}
guard let data = data else {
print("No data received")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let jsonDictionary = json as? [String: Any] {
DispatchQueue.main.async {
self.jsonData = jsonDictionary
}
}
} catch {
print("JSON parsing error: \(error)")
}
}.resume()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
More than 1 year has passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme