0

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"
       }
    ]
 }
5
  • Could you include a sample JSON file you are parsing? Even better, a playground that demonstrates the issue. Commented Mar 22, 2017 at 3:46
  • stackoverflow.com/questions/41734982/… JSON Parsing is mentioned in thousands of questions Commented Mar 22, 2017 at 4:01
  • @kkoltzau you got the JSON file as well Commented Mar 22, 2017 at 10:06
  • @UmairAfzal this don't help me here :/ Commented Mar 22, 2017 at 10:06
  • @PavlosNicolaou please check my answer Commented Mar 22, 2017 at 10:19

1 Answer 1

2

As an update, the following code, which can run in a playground, demonstrates that the original code runs fine:

class Messages: NSObject {
    var id: String?
    var date: String?
    var text: String?
}

var messagesSet = [Messages]()
let str = "{\"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\"}]}"
let data = str.data(using:String.Encoding.utf8)
do {
    let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
    if let messageList = jsonData["messages"] as? [Any] {
        for messageInfo in messageList {
            let message = Messages()
            if let info = messageInfo as? [String:Any] {
                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)
                messagesSet
            } else {
                NSLog("Failed to get message info dicgtionary")
            }
        }
        NSLog("Completed with data: \(messagesSet.count)")
    } else {
        NSLog("Failed to get messages")
    }
} catch let error {
    print("Decoding error \(error)")
}

The issue, as far I can tell (for those who are interested in what happened) is that the OP thought that their inability to print a Messages object was due to a code issue. Whereas it can simply be fixed by overriding the description property of the Messages object (since it is a sub-class of NSObject) as follows:

class Messages: NSObject {
    var id: String?
    var date: String?
    var text: String?

    override var description: String {
        return "Message: ID - \(id), Content - \(text)"
    }
}

This is just for the reference of anybody else who might be interested.

Sign up to request clarification or add additional context in comments.

8 Comments

the problem is that in the if statements I can print message.text and get the message.. but when I append the message into the messagesSet I cannot use the message after that. The issue is adding data from an object in an array.
I understand that, but the code you've provided does not have any issues which could cause what you are seeing. Which is why having the full project code would help in figuring out what is going on ...
See the code that I just added to my answer. If you put that in a playground, it works. So you can just modify that to make any additional changes you need to make.
You'd simply refer to the relevant property of the object instance. For example, use let msg = messagesSet[0] to get one instance of Messages from the array and then use msg.text to get the text property and msg.id to get the id property.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.