更新当前用户的解析对象,而不是创建重复的条目

时间:2016-08-07 17:44:32

标签: ios swift parsing

我想让用户更新他们的位置。当我尝试保存数据时,它会创建一个重复的条目,而不是更新旧信息。我有一个heroku解析服务器部署到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()

        }
    }
}

}

2 个答案:

答案 0 :(得分:0)

似乎point只设置一次。尝试从CLLocationManagerDelegate协议添加以下方法。

func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
        // updated coordinate
        point = PFGeoPoint(location: manager.location!)        
}

答案 1 :(得分:0)

好的,我发现了我的问题。我的问题是我在查询用户而不是.username。

    var user = PFUser.currentUser()?.username

此外,我需要设置要更新的元素的强制,如果查询失败,则创建一个新实例。

            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()
        }

    }