I'm trying to setup a picker with dynamic contents and a custom ID, but i'm running into issues getting this working. I'm probably going about this totally wrong.
I'm getting information from a my website using the below code.
function unnamedDecks($pdo) {
$sql = "SELECT u.ID, u.description, c.name
FROM deck_unnamed AS u
LEFT JOIN deck_categories AS c ON c.ID = u.category
WHERE deck IS NULL;";
$q = $pdo->prepare($sql);
$q->execute();
if($q->errorCode() != 0) {
$errors = $q->errorInfo();
echo($errors[2]);
}
foreach ($q->fetchAll() as $row) {
$unnamed[] = array('ID' => $row['ID'], 'name' => $row['name'], 'description' => $row['description']);
}
$arr = array(
"decks" => (isset($unnamed)) ? $unnamed : "0",
);
echo json_encode($arr);
}
An example of the response from the function is
{"decks":[{"ID":"69","name":"???","description":"???"},{"ID":"X1","name":"???","description":"???"}]}
Then in the app processing it using
func getUnnamedDecksList() async -> UnnamedDeckList? {
let downloadTask = Task { () -> UnnamedDeckList in
let url : String = "****"
var components = URLComponents(string: url)!
components.queryItems = [
URLQueryItem(name: "action", value: "unnamedDecks")
]
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let (data, _) = try await URLSession.shared.data(from: components.url!)
let result = String(data: data, encoding: .utf8) ?? ""
let jsonData = result.data(using: .utf8)!
let dataRes: UnnamedDeckList = try! JSONDecoder().decode(UnnamedDeckList.self, from: jsonData)
return dataRes
}
let result = await downloadTask.result
do {
let categories = try result.get()
return categories
} catch {
print("Unknown error.")
}
return nil
}
The setup of the UnnamedDeckList & related class
struct UnnamedDeck : Decodable {
let name : String
let ID : String
let description : String
}
struct UnnamedDeckList : Decodable {
let decks : [UnnamedDeck]
}
Then trying to display with a picker, where UnnamedDeck.name is what's shown, and ID is it's ID, but this is where I'm getting stuck.
I can get the picker to show what I want by doing the below, but I can't get the ID using it.
let catsArray = getCategoryList()
Picker("", selection: $category) {
ForEach(catsArray, id: \.self) {
Text($0)
}
}
getCategoryList()and how you declare its elements, also show how you declarecategory. These should be of the same type. In yourPicker, you should make the elements of your catsArrayIdentifiable, then useForEach(catsArray){ item in ...}. You then have to addText(item).tag(item)and make sure the tagitemis of the same type as yourcategory.