I have the following data in JSON Format:
{"contacts":[{"name":"Bob"},{"name":"Greg"},{"name":"Sally"},{"name":"Will"},{"name":"George"},
{"name":"Charlie"},{"name":"Alice"},{"name":"Albert"},{"name":"Alfred"},{"name":"Bart"},
{"name":"Dan"},{"name":"Dave"},{"name":"Eddie"},{"name":"Frank"},{"name":"Ralph"},{"name":"Tammy"},
{"name":"Tom"},{"name":"James"},{"name":"John"},{"name":"Quincy"},{"name":"Peter"},{"name":"Richard"},
{"name":"Zachary"},{"name":"Zbiginew"},{"name":"Tentacool"},{"name":"Tentacruel"},{"name":"Metapod"},
{"name":"Meowth"}]}
The JSON is stored in some URL, and I want to gather the info and put it into an array that, ideally looks like [Bob, Greg, Sally, Will...]
.
Right now I've got the code:
let jsonLocation = "http://raw.myjsondatalocation.com/contact.json"
guard let url = URL(string: jsonLocation) else {
return
}
URLSession.shared.dataTask(with: url){ (data,response,error) in
guard let data = data else { return }
do{
let decoder = JSONDecoder()
let ListOfNames = try decoder.decode(Contact.self, from:data).contacts
// print(myListOfContacts)
print(ListOfNames[0].name)
}
catch let jsonErr{
print("Error!",jsonErr)
}
}.resume()
I use a Codable to parse JSON. This seems to work fine, as it returns an array of items with the form [[ContactList.Contact.PersonalInfo(name: "Bob")...
and when I am calling print(ListOfNames[0].name)
, it appropriately returns "Bob" but if I put it outside of URLSession, it says it's unresolved.
The array of names will later be put into a TableView. I really don't know how to solve this. Can anyone give me a hand here?