从Parse中检索信息

时间:2015-12-19 16:58:42

标签: ios swift parse-platform

我正在尝试构建一个聊天应用程序,但我对此代码有疑问:

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!)

          }
        }
      }
    }

我需要从Parse检索数据,但.findObjectsInBackgroundWithBlock方法告诉我它无法将AnyObject类型的值转换为Void in。如何解决此问题?提前谢谢。

2 个答案:

答案 0 :(得分:2)

请尝试这样:

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)")
    }
}

(没有正确的校对,但你应该可以从中得到它)

答案 1 :(得分:1)

对于记录,这个问题有很多重复的问题 - 我知道,因为我在将Parse代码转换为Swift 2.1后遇到了同样的问题。 因此,请在发布问题之前再做一些研究。通常,SO甚至会在您输入时向您提示类似的问题......

至于答案,Parse API不会强制您在查询的完成块中将对象强制转换为AnyObject,因此它看起来像这样:

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

....等