To further test, I mimicked your JSON, considering it would look like this (each element with an id and a name). They are in fact Dictionaries:
[{"id":"First","name":"One"},
{"id":"Second","name":"Two"},
{"id":"Third","name":"Three"}]
If so, the test code (I commented out the url part to replace by hardwired data)
typealias MyDict = [String: String] // A dictionary is defined as [key:Value]
struct Item : Codable { // Need Codable to be used by Decoder
var id: String // Identical to the key:value of the JSON (you can later change the name using CodingKeys …
var name: String
}
// ----------- this part for hardwired test --------------
// This to create data by hand ; in your case, data will come from php request
let one = Item(id: "First", name:"One")
let two = Item(id: "Second", name:"Two")
let three = Item(id: "Third", name:"Three")
let itemData = [one, two, three] // Here, 3 elements in JSON
let data = try JSONEncoder().encode(itemData) // create the data that you'll in fact retrieve from url
print("JSON Data", String(data: testJSONData, encoding: .utf8)!) // To check what is in data
// -------------------------------------------------------
var quotes: [MyDict] { // back to array of Dict
var output: [MyDict] = []
// ----------- 3 lines commented for test with hardwired data --------------
// if let url = URL(string:"https://www.TEST.com/test_connection.php") {
// URLSession.shared.dataTask(with: url) { (data, response, error) in
// if let data { // data were built with encode, but that would work with url if you uncomment those 3 lines
if let json = try? JSONDecoder().decode([MyDict].self, from: data) {
output = json
}
// }
// }
// }
return output
}
print("quotes", quotes)
You get this (once again, dictionaries are not ordered):
JSON Data [{"id":"First","name":"One"},{"id":"Second","name":"Two"},{"id":"Third","name":"Three"}]
quotes [["name": "One", "id": "First"], ["name": "Two", "id": "Second"], ["name": "Three", "id": "Third"]]
if json in server is like this:
[{"id":"First","name":"One"},
{"id":"Second","name":"Two"},
{"id":"Third","name":"Three"}]
Your own code should then be:
struct Item : Codable { // Need Codable to be used by Decoder
var id: String // Identical to the key:value of the JSON (you can later change the name using CodingKeys …
var name: String
}
var quotes: [Item] {
var output: [Item] = []
if let url = URL(string:"https://www.TEST.com/test_connection.php") {
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data {
if let json = try? JSONDecoder().decode([Item].self, from: data) {
output = json
}
}
}
}
return output
}