it's my first message in the forum and i hope to post it right.
I'm trying to create a Dynamic List in SwiftUI that get's updated as soon as the user type something inside a textfield.
The list use the API of viaggiatreno.it which is the service from Italian Train company.
The specific link i'll use returns the list of the train stations that begin with the string provided to a certain URL.
I've created a Station Class as follows:
struct Station: Decodable, Identifiable {
var iid = UUID()
var name : String
var id: String
}
And a StationFetcher class that fetches the API url initialized with a string that is the string the the user will pass from the text field:
import Foundation
public class StationFetcher : Decodable, ObservableObject {
var stations = [Station]()
var search = ""
init(search: String) {
getJsonData(string: search)
}
func getJsonData(string: String) {
let url = URL(string: "http://www.viaggiatreno.it/viaggiatrenonew/resteasy/viaggiatreno/cercaStazione/" + string)
//string is the initial string of the station
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error!)
} else {
if let urlContent = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: urlContent , options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
for i in 0..<jsonResult.count {
if let station = jsonResult[i] as AnyObject? {
if let nameStation = station["nomeLungo"] as! String? {
if let idStation = station["id"] as! String? {
let searchItem = Station(name: nameStation, id: idStation)
DispatchQueue.main.async {
self.stations.append(searchItem)
}
}
} else {
print("error catching dictionary value")
}
}
}
} catch {
print("JSON Processing failed")
}
}
}
}
task.resume()
}
}
How can i manage this in the main SwiftUI View?
import SwiftUI
struct Departure: View {
@State public var selectedStation = ""
@State private var departureDate = Date()
@ObservedObject var fetcher = StationFetcher(search: "")
var body: some View {
NavigationView {
Form {
Section(header: Text("Cerca Stazione di partenza:")) {
TextField("Da dove parti?...", text: $selectedStation)
}
Section(header: Text("Orario:")) {
DatePicker(selection: $departureDate) {
Text("Partenza")
}
}
Section(header: Text("Lista stazioni")){
List(fetcher.stations) { station in
Text(station.name)
}
}
}
.navigationBarTitle("Partenza")
}
}
}
Thanks to everybody