Ozan
Ozan

Reputation: 39

How to show Nested JSON values into the pickerview in Swift UI?

I want user to select the city and district of that city. When I select the city I want to list the districts of that city in the pickerview. I also want to show the selection of the city and the selection of the district in Text.

struct locationView: View {


@State var selectedFrameworkIndex = 0
@State var tap1 : Bool = false

@ObservedObject var cityfetch = cityFetcher()

var selectedCityName: String? {
    if !cityfetch.cities.isEmpty && selectedFrameworkIndex < cityfetch.cities.count {
        return cityfetch.cities[selectedFrameworkIndex].city_name
    } else {
        return nil
    }
}

var body: some View {
    
          
            VStack{
                
                
                Picker(selection: $selectedFrameworkIndex, label: Text("")) {
                    ForEach(0 ..< cityfetch.cities.count, id: \.self) {
                        
                        Text(self.cityfetch.cities[$0].city_name)
                    }
                }.padding(.trailing, 50)
                    .id(UUID())
                
                
                Picker(selection: $selectedFrameworkIndex, label: Text("")){
                    ForEach(0 ..< cityfetch.cities.count, id: \.self) {
                        
                        Text(self.cityfetch.cities[$0].district_name)
                    }
                }.padding(.trailing, 50)
                    .id(UUID())
                
            }
            
            
            
            Text("Seçiminiz: \(selectedCityName ?? "")")
                .font(.system(size: 20, weight: .regular, design: .rounded))
            
            
        }

struct city : Decodable, Identifiable{

let id = UUID()
let city_id : Int
let city_name : String
let district_id : Int
let district_name : String
}

My class is following..

class cityFetcher : ObservableObject{

@Published var cities = [city]()


init() {
    loadCity()
    
}
func loadCity(){
    
    let url = URL(string: "https://raw.githubusercontent.com/midorikocak/turkish-cities-districts/master/data/il-ilce.json")
    URLSession.shared.dataTask(with: url!) { (data, response, error) in
        do{
            let cities = try JSONDecoder().decode([city].self, from: data!)
            DispatchQueue.main.async {
                self.cities = cities
                
            }
                
            
        }   catch{
            print("Error")
        }
    }.resume()
    
    
}

}

I also posting my JSON informations as an image.

enter image description here

Upvotes: -1

Views: 449

Answers (1)

Zeona
Zeona

Reputation: 454

Add function getUniqiueCities() in cityFetcher to create an array of unique cities and call this function after self.cities = cities. Create @Published var uniqueCities : [city] = [] in cityFetcher.

func getUniqiueCities() {
        var uniqueCities: [city] = []
        for city in self.cities {
            let isExists =  uniqueCities.contains{ item in
                return item.city_name == city.city_name
            }
            if !isExists {
              uniqueCities.append(city)
            }
        }
        self.uniqueCities =  uniqueCities
    }

Run a loop for unique cities and display districts based on unique city name. Update LocationView with below code

struct locationView: View {
    @State var selectedFrameworkIndex = 0
    @State var selectedCityIndex = 0
    @State var tap1 : Bool = false
    @ObservedObject var cityfetch = cityFetcher()

    var selectedCityName: String? {
        if !self.cityfetch.uniqueCities.isEmpty && selectedFrameworkIndex < self.cityfetch.uniqueCities.count {
            return self.cityfetch.uniqueCities[selectedFrameworkIndex].city_name
        } else {
            return nil
        }
    }

    var body: some View {
        VStack{
            Picker(selection: $selectedFrameworkIndex, label: Text("")) {
                ForEach(0 ..< self.cityfetch.uniqueCities.count, id: \.self) {
                    Text(self.cityfetch.uniqueCities[$0].city_name)
                }
            }.padding(.trailing, 50)
            .id(UUID())
            Picker(selection: $selectedCityIndex, label: Text("")){
                ForEach(0 ..< self.getFilteredDistricts().count, id: \.self) {
                    Text(self.getFilteredDistricts()[$0].district_name)
                }
            }.padding(.trailing, 50)
            .id(UUID())
            
        
                  
        Text("Seçiminiz: \(selectedCityName ?? "")")
            .font(.system(size: 20, weight: .regular, design: .rounded))
        }
    }
    
    func getFilteredDistricts() -> [city] {
        return self.cityfetch.cities.filter({$0.city_name == self.cityfetch.uniqueCities[selectedFrameworkIndex].city_name})
    }
    
}

UPDATE

As per comments, added code to get selectedDistrict:

var selectedDistrict: String? {
        if !self.getFilteredDistricts().isEmpty && selectedCityIndex < self.getFilteredDistricts().count {
            return self.getFilteredDistricts()[selectedCityIndex].district_name
        } else {
            return nil
        }
    }

Upvotes: 0

Related Questions