Berkehan Atikeler Berkehan Atikeler - 19 days ago 6
Swift Question

Parse Swift Saving Multiple Objects

Parse
and
Swift 3.0


I am trying to save multiple data one at a time but all the code does is that it saves every file to the same
ObjectId
. Hence overriding the previous saves. I am not very experience in coding and kind of lost. If there is a better way to do this I am open to suggestions. If you need anymore information I would gladly provide it.

func importToParse() {
var i = 1
var data = PFObject(className:"Annotation")
for dataFromDict in dataDict {
data["title"] = dataFromDict["title"]
data["place"] = dataFromDict["place"]
data["phoneNumber"] = "+9" + (dataFromDict["phoneNumber"]?.replacingOccurrences(of: ".", with: ""))!
data["thingsToEat"] = dataFromDict["thingsToEat"]
data["coordinates"] = PFGeoPoint(latitude: (dataFromDict["lat"] as! NSString).doubleValue,longitude: (dataFromDict["long"] as! NSString).doubleValue)
data.saveInBackground(block:) {
(success: Bool, error: Error?) -> Void in
if (success) {
// The object has been saved.
print("Finished #" + String(i))
i += 1
} else {
// There was a problem, check error.description
}
}
}
}

Answer

I think you need to create the object inside the loop

func importToParse() {
    var i = 1
    for dataFromDict in dataDict {
        var data = PFObject(className:"Annotation")
        data["title"] = dataFromDict["title"]
        data["place"] = dataFromDict["place"]
        data["phoneNumber"] = "+9" + (dataFromDict["phoneNumber"]?.replacingOccurrences(of: ".", with: ""))!
        data["thingsToEat"] = dataFromDict["thingsToEat"]
        data["coordinates"] = PFGeoPoint(latitude: (dataFromDict["lat"] as! NSString).doubleValue,longitude: (dataFromDict["long"] as! NSString).doubleValue)
        data.saveInBackground(block:) {
            (success: Bool, error: Error?) -> Void in
            if (success) {
                // The object has been saved.
                print("Finished #" + String(i))
                i += 1
            } else {
                // There was a problem, check error.description
            }
        }
    }
}