RGM-79FP GM Striker RGM-79FP GM Striker - 2 months ago 22
Swift Question

Saving to Parse in a while loop swift

So I have a problem where I call save after putting some items in an object. I go to an API and I download some info and then I save it to another system for temporary use, however the .save() seems to only save 2 items, with no special pattern in which it selects. Can someone explain what the problem is?

let url = URL(string: link)
let spots = PFObject(className:"spot")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in

if error != nil {
print(error)
}
else{
if let urlContent = data{

do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
let results = (jsonResult as! NSDictionary)["results"]
let venueList = (results as! NSArray)
//print(jsonResult)
var i = 0
while i < venueList.count{
let venues = venueList[i] as! NSDictionary
let name = venues["name"] as! String
let geometry = venues["geometry"] as! NSDictionary
let location = geometry["location"] as! NSDictionary
let cLat = location["lat"] as! Double
let cLon = location["lng"] as! Double
let vPoint = PFGeoPoint(latitude: cLat, longitude: cLon)
//print(name," ", vPoint)
spots["venue"] = name
spots["name"] = vPoint
do{
try HotSpots.save()
print("Saved! ",name," ", vPoint)
}
catch{
print("Save Error")
}
i+=1
}




}
catch{
print("JSON Error")
}
}
}
}
task.resume()
}

Answer

The issue is that you're saving the two values always in the same PFObject instance.

Move the line let spots = PFObject(className:"spot") in the loop.

Comments