Hello everyone,
I'm trying to create an iOS app with Swift for the first time and I've encountered an error that I can't solve. I've searched and googled a lot but somehow I can't find anything.
So, the app displays city names and when you click on a city, it should then display categories such as restaurants or doctors. The addresses should come from a json file that is on my hosting. As soon as I write the code with the json file, the categories disappear, there is no error message from xcode. Do you have any idea what else I could try. This is the code, and the json file.
swift code:
timport SwiftUI
struct CitySelectionView: View {
let cities = ["Hamburg", "Berlin", "Köln", "München", "Frankfurt", "Stuttgart"]
var body: some View {
NavigationView {
List(cities, id: \.self) { city in
NavigationLink(destination: CategorySelectionView(city: city)) {
Text(city)
}
}
.navigationTitle("Städte")
}
}
}
struct CategorySelectionView: View {
let categories = ["Restaurants", "Bars", "Ärzte", "Supermärkte", "Freizeit"]
let city: String
@State private var restaurants: [Restaurant] = []
var body: some View {
VStack {
Text("Wähle eine Kategorie für \(city):")
.font(.title)
.padding()
List(restaurants, id: \.name) { restaurant in
VStack(alignment: .leading) {
Text(restaurant.name)
.font(.headline)
Text(restaurant.address)
.font(.subheadline)
}
}
.onAppear {
if city == "Hamburg" {
downloadRestaurantData()
}
}
}
.navigationTitle("\(city)")
}
func downloadRestaurantData() {
guard let url = URL(string: "http://www.digi-nova.de/xmlapp/hamburg/restaurants/restaurantshamburg.json") else {
print("Invalid URL")
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
print("Error: \(error?.localizedDescription ?? "Unknown error")")
return
}
do {
let decodedData = try JSONDecoder().decode([Restaurant].self, from: data)
DispatchQueue.main.async {
self.restaurants = decodedData
}
} catch {
print("Failed to decode JSON data: \(error.localizedDescription)")
}
}.resume()
}
}
struct Restaurant: Codable, Identifiable {
var id = UUID()
let name: String
let address: String
let zip: String
let city: String
let phone: String
let opening_hours: String
let map_link: String
}
struct ContentView: View {
var body: some View {
CitySelectionView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
in the code is the link to the json file