I have a UIPickerView that gets data from JSON and presents it in two columns, one that shows two columns, producer and product using the following:
if let url = URL(string: "https://www.example.com/example"),
let data = try? Data(contentsOf: url),
let tmpValues = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String:String]] {
let tempCategories = tmpValues?.reduce(into: [String:[String]](), { (dict, value) in
if let producer = value["producer"], let product = value["product"] {
dict[producer, default:[]].append(product)
}
})
for category in (tempCategories ?? [:]) {
allCategories.append(Category(name: category.key, items: category.value))
}
pickerView.reloadAllComponents()
}
The issue is while the JSON presents the array in alphabetical order, the PickerView presents the array in random orders every time it is opened, how can this be fixed.
First of all you are strongly discouraged from loading data from a remote URL with synchronous
Data(contentsOf. From the documentationSecondly, a dictionary is unordered. You could sort the keys and populate the picker source array this way