Edoardo Riggio
Edoardo Riggio

Reputation: 83

Retrieving info from Parse

I am trying to build a chat application, but I have a problem with this code:

func loadData() {

        let FindTimeLineData: PFQuery = PFQuery(className: "Message")
        FindTimeLineData.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, NSError) -> Void in

            self.MessagesArray = [String]()

            for MessageObject in objects {

                let messageText: String? = (MessageObject as! PFObject) ["Text"] as? String

                if messageText != nil {

                    self.MessagesArray.append(messageText!)

          }
        }
      }
    }

I need to retrieve data from Parse, but the .findObjectsInBackgroundWithBlock method tells me that it cannot convert a value of type AnyObject into Void in. How can I resolve this problem? Thanks in advance.

Upvotes: 0

Views: 49

Answers (2)

jesses.co.tt
jesses.co.tt

Reputation: 2729

For the record, there are LOTS of duplicate questions with this problem - i know, as I had the same problem after converting Parse code to Swift 2.1. So, please do a little more research before you post a question. Often, SO even hints at you similar questions as you are typing...

As for the answer, the Parse API doesn't force you to cast the object as AnyObject anymore in the completion block of a query, so it can look just like this:

 query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
        if let messages = objects {
            for message in messages {

.... etc

Upvotes: 1

Marius Waldal
Marius Waldal

Reputation: 9932

Try it like this instead:

var query = PFQuery(className: "Message")
query.findObjectsInBackgroundWithBlock {
    (remoteObjects: [PFObject]?, error: NSError?) -> Void in

    if error == nil {
        print("Retrieved \(remoteObjects!.count) messages from server.")
        self.MessagesArray = [String]()     // By convention, you should name this "messagesArray" instead, and initialize it outside this method

        for messageObject in remoteObjects {

            if let messageText: String? = messageObject["Text"] as? String {
                self.messagesArray.append(messageText)
            }
        }
    } else {
         print("Error: \(error!) \(error!.userInfo)")
    }
}

(not properly proof-read, but you should be able to get it to work from this)

Upvotes: 2

Related Questions