Pascal Ackermann Pascal Ackermann - 18 days ago 10
Swift Question

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.

My class:

enter image description here

Answer

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.