简体   繁体   English

快速保存以进行解析

[英]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. 我使用API​​,然后下载了一些信息,然后将其保存到另一个系统中以供临时使用,但是.save()似乎只保存了2个项目,没有选择的特殊模式。 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()
}

The issue is that you're saving the two values always in the same PFObject instance. 问题是您总是将两个值保存在同一PFObject实例中。

Move the line let spots = PFObject(className:"spot") in the loop. 在循环中移动let spots = PFObject(className:"spot")的行。

PS: Use Swift native types. PS:使用Swift本机类型。 For example this is more efficient 例如,这更有效

let location = geometry["location"] as! [String:Double]
let cLat = location["lat"]!
let cLon = location["lng"]!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM