So I have this object:
class Messages: NSObject {
var id: String?
var date: String?
var text: String?
}
And I am parsing data using URLSession and then I want to create an array to add the messages in it. The problem is when I print messages.id or messages.text I can see the data but when I append them in an array: messagesSet = [Messages]() and print the text of the array I get something like [].
Here is the code to parse the data:
//Initiate Getting Messages
func getMessages(url: URL, completion: @escaping DownloadComplete) {
let dataTask = URLSession.shared.dataTask(with: url) {
(data, response, error) in
self.didFetchMessages(data: data, response: response!, error: error, completion: completion)
}
dataTask.resume()
}
//Callback for URLSession for getMessages
private func didFetchMessages(data: Data?, response: URLResponse, error: Error?, completion: @escaping DownloadComplete) {
do {
let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
guard let messageList = jsonData["messages"] as? [Any] else {
completion(nil, false)
return
}
for messageInfo in messageList {
let message = Messages()
guard let info = messageInfo as? [String:Any] else {
completion(nil, false)
return
}
if let id = info["id"] as? String {
message.id = id
}
if let date = info["date"] as? String {
message.date = date
}
if let text = info["text"] as? String {
message.text = text
}
messagesSet.append(message)
print(messagesSet)
}
completion(messagesSet, true)
} catch let error {
print("Decoding error \(error)")
}
}
Thank you for your help.. I hope this info are enough to find the solution to this problem.
Here is the JSON Response:
{
"messages": [
{
"id": "4323",
"date": "07/01/17 23:22",
"text": "This is a test message"
},
{
"id": "4324",
"date": "07/01/17 23:23",
"text": "This is a test message 2"
},
{
"id": "4326",
"date": "07/01/17 23:25",
"text": "This is a test message3"
}
]
}