Error while retrieving data from parse.com

Hello I want to get some data from my parse.com class called “Tags” in this class there are two 3 cols “objectID”, “username” and “tagtext”. I want to read a record finding by ID and afterwords I want to save “useername” and “tagtext” into two strings. I have done it like it is in the parse.com documentation:

@IBAction func readAction(sender: UIButton) {

    var query = PFQuery(className:"Tags")
    query.getObjectInBackgroundWithId("IsRTwW1dHY") {
        (gameScore: PFObject?, error: NSError?) -> Void in
        if error == nil && gameScore != nil {
            println(gameScore)
        } else {
            println(error)
        }
    }

    let username = gameScore["username"] as! String
    let tagtext = gameScore["tagtext"] as! String

    println(username)
    println(tagtext)   

}

I get an error called fatal error: unexpectedly found nil while unwrapping an Optional value , please tell me what is wrong in my code.

  • CoreData: error: Serious application error. Exception was caught during Core Data change processing
  • Ambiguous reference to member when using ceil or round
  • Get the device's phone number programmatically
  • Uploading an image from iOS to PHP
  • Autolayout height equal to MAX(multiple view heights)
  • How to catch all iOS Push Notifications with different user actions including tap on app icon
  • My class:

    enter image description here

    2 Solutions Collect From Internet About “Error while retrieving data from parse.com”

    The problem is that:

    let username = gameScore["username"] as! String
    let tagtext = gameScore["tagtext"] as! String
    

    gameScore["username"] and gameScore["tagtext"] can return nil values, and when you say as! String you say that it will be a String, and it is nil.

    Try something like:

    let username = gameScore["username"] as? String
    let tagtext = gameScore["tagtext"] as? String
    

    your error is happening because of that, but your final code should look like this:

    @IBAction func readAction(sender: UIButton) {
    
      var query = PFQuery(className:"Tags")
      query.getObjectInBackgroundWithId("f3AXazT9JO") {
        (gameScore: PFObject?, error: NSError?) -> Void in
    
        let username = gameScore["username"] as? String
        let tagtext = gameScore["tagtext"] as? String
    
        println(username)
        println(tagtext) 
        if error == nil && gameScore != nil {
           println(gameScore)
        } else {
           println(error)
        }
      }
    }
    

    Because the getObjectInBackgroundWithId is async.

    You are trying to read from your response object gameScore but it is still nil because getObjectInBackgroundWithId is an asynchronous method meaning that it will return a result once it is finished. Put the two lines inside the handler and start from there.