简体   繁体   中英

Retrieve object from Parse with Swift

I'm developing a simple iOS application. It's a simple quiz app. I'm using Parse to store my questions, answers etc. I've read all the documentation and cannot find why this code to retrieve an object is not working.

var query = PFQuery(className: "Test_Questions")
query.getObjectInBackgroundWithId("cJzv2JdMej", block: {
    (questionObject: PFObject?, error: NSError?) -> Void in

    let thisQuestion = questionObject["question"] as! String
    //Error here: AnyObject is not convertible to String

})

Your help would be much appreciated!

Console Output:

Optional(What statement must come before an else statement?)

You should try this instead:

var query = PFQuery(className: "Test_Questions")
query.getObjectInBackgroundWithId("cJzv2JdMej", block: {
(questionObject: PFObject?, error: NSError?) -> Void in
    if error == nil {
        println(questionObject)
        //if there's info in the console you know the object was retrieved
        let thisQuestion = questionObject["question"] as? String

    } else {
        println("Error occurred retrieving object")
    }
})

If that doesn't work you can also try let thisQuestion = questionObject.valueForKey("question") . Also make sure that Parse is actually returning an object by adding a print statement such as println(questionObject) after it has been retrieved so that you know Parse is returning an object.

Got it!

var query = PFQuery(className: "Test_Questions")
    query.getObjectInBackgroundWithId("cJzv2JdMej", block: {
        (questionObject: PFObject?, error: NSError?) -> Void in

        let thisQuestion: AnyObject! = questionObject!.valueForKey("question")

        self.question.text = thisQuestion as? String

        })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM