Jarad Kears Jarad Kears - 3 months ago 23
Swift Question

Updating parse object for current user instead of creating duplicate entry

I am trying to let the user update their location. When I try to save the data it creates a duplicate entry instead of updating the old information. I have a heroku parse server deployed to a mongolabs db.

class DropLoc: UIViewController, CLLocationManagerDelegate {

var user = PFUser.currentUser()
var post = PFObject(className:"Post")
var query = PFQuery(className:"Post")
var point: PFGeoPoint!
let porta = CLLocationManager()


override func viewDidLoad() {
super.viewDidLoad()


var curGate = porta.location

self.porta.delegate = self
self.porta.desiredAccuracy = kCLLocationAccuracyBest
self.porta.requestWhenInUseAuthorization()
self.porta.startUpdatingLocation()
point = PFGeoPoint(location: curGate)


query.whereKey("user", equalTo: user!)
query.findObjectsInBackgroundWithBlock {(objects: [PFObject]?, error: NSError?) -> Void in
if error != nil {
print(error)
}else{
self.post["user"] = self.user ?? NSNull()
self.post["location"] = self.point ?? NSNull()
self.post.saveInBackground()

}
}
}


}

Answer

Ok I found out what my issue was. My problem was that I was querying user and not .username.

    var user = PFUser.currentUser()?.username

Also I needed to set the force the elements to update and if the query fails create a new instance.

            query.whereKey("user", equalTo: user!)
    query.getFirstObjectInBackgroundWithBlock() {(uobject: PFObject?, error: NSError?) -> Void in
        if error != nil {
            self.post["user"] = self.user ?? NSNull()
            self.post["location"] = self.point ?? NSNull()
            self.post.saveInBackground()
        }else if let uobject = uobject{
            uobject["user"] = self.user ?? NSNull()
            uobject["location"] = self.point ?? NSNull()
            uobject.saveInBackground()
        }

    }