1

I am making a simple app, and implementing the userInformation part. The user can edit his info, but I have trouble that if user doesn't put any info, it will crash when I try to retrieve data from an undefined column.

This is my code to retrieve the user data. If there is data to parse it won't crash, otherwise it will.

    let nickName = PFUser.currentUser()?.objectForKey("nickName") as! String

So I am asking how can I handle retrieving undefined value before crash? (please write full code for me)

Is there a way I can check value before I retrieve it?

///like this
if (value in parse  == "ABC") {
    print("yes")
}
Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
veryNew
  • 125
  • 1
  • 13
  • this might help http://stackoverflow.com/questions/25779392/swift-optional-text-in-optional-value – sakhunzai Sep 28 '15 at 04:08
  • You're telling it to crash if it can't unpack to a string - just stop doing that... – Wain Sep 28 '15 at 06:52
  • I don't quite understand the question. Why don't you check if `objectForKey` returns nil or not before unwrap the underlying value? – Siyuan Ren Sep 28 '15 at 07:00

2 Answers2

2

if you want to retrieve objects (only defined objects) through query then u need to see

 query.whereKeyExists("nickName");

if u simply want to check retrieved coulmn's value is defined or not you can simply use

if(user["nickName"])
{
  // nickname exists for user ;
} 
Waseem Lateef
  • 151
  • 1
  • 6
0

Here, Try this code:

let query = PFUser.query()
    query!.whereKey("username", equalTo: "abcd")
    query!.findObjectsInBackgroundWithBlock({
        (object, error) -> Void in
        if (object != nil) {
            if(object!.count != 0)
            {
                for messageObject in object! {
                    let photoUploaded : Bool = ((messageObject as! PFObject)["photoUploaded"] as? Bool)!
                    if (photoUploaded == true) {
                        if let userPicture = messageObject["profilePic"] as? PFFile {
                            userPicture.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
                                if (error == nil) {
                                    let imageData = imageData
                                    let image = UIImage(data: imageData!)
                                    self.createrImage.image = image
                                } else {
                                    // Error handling
                                }
                            }
                        }

                    }
                }
            } // object is undefined here
        } // else is added here to get object is nill
    })

I am checking if the photo is uploaded with the user data. If is uploaded, I will get true as Bool value, if not uploaded, then false . If not defined, add else part and breakpoint at the comment to avoid crash. update me in case of any issue

AAA
  • 1,957
  • 4
  • 23
  • 42