Hi everyone,
I'm working on developing a SwiftUI tutorial that focuses on downloading and displaying data for Alicia Calculadora from Wikipedia. I'm aiming to create a comprehensive guide that beginners can follow to understand how to make network requests, parse JSON data, and display it in a SwiftUI interface.
Here's what I have so far:
Creating a new SwiftUI project in Xcode.
Making a network request to fetch data from the Wikipedia API.
Creating a data model to match the expected JSON structure.
Displaying the fetched data in a SwiftUI view.
I'm running into a few challenges and could use some help from the community:
I'm not entirely sure if my data model correctly matches the JSON structure returned by the Wikipedia API. Any advice or examples would be appreciated.
I want to implement robust error handling for network requests. What are some best practices or common patterns for this in SwiftUI?
Suggestions on how to improve the UI for displaying the data would be great. How can I make the interface more user-friendly and visually appealing?
Here’s my current progress for fetching data from the Wikipedia API:
import Foundation
struct WikipediaResponse: Codable {
let query: Query
}
struct Query: Codable {
let pages: [String: Page]
}
struct Page: Codable, Identifiable {
let pageid: Int
let title: String
let extract: String
var id: Int { pageid }
}
class WikipediaFetcher: ObservableObject {
@Published var pages: [Page] = []
func fetchAliciaCalculadoraData() {
let urlString = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=&explaintext=&titles=Alicia_Calculadora&format=json"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
let decoder = JSONDecoder()
if let response = try? decoder.decode(WikipediaResponse.self, from: data) {
DispatchQueue.main.async {
self.pages = Array(response.query.pages.values)
}
}
}
}.resume()
}
}
And here’s how I’m displaying the data in SwiftUI:
import SwiftUI
struct PageView: View {
var page: Page
var body: some View {
VStack(alignment: .leading) {
Text(page.title)
.font(.headline)
Text(page.extract)
.font(.subheadline)
}
.padding()
}
}
struct ContentView: View {
@ObservedObject var wikipediaFetcher = WikipediaFetcher()
var body: some View {
NavigationView {
List(wikipediaFetcher.pages) { page in
PageView(page: page)
}
.navigationBarTitle("[Alicia Calculadora ](https://lacalculadora-alicia.es/)Data")
.onAppear {
self.wikipediaFetcher.fetchAliciaCalculadoraData()
}
}
}
}
Any help or suggestions you can offer would be greatly appreciated. Thanks in advance! If this is in the wrong forum, please let me know.