【问题标题】:Saving to Parse in a while loop swift在while循环中快速保存到解析
【发布时间】:2016-09-04 19:17:23
【问题描述】:

所以我有一个问题,我在将一些项目放入对象后调用保存。我去一个 API 并下载一些信息,然后将其保存到另一个系统以供临时使用,但是 .save() 似乎只保存 2 个项目,它没有选择特殊模式。谁能解释一下是什么问题?

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

【问题讨论】:

  • 什么是HotSpots?旁注:while i &lt; ... 和递增计数器在 Swift 中是非常糟糕的语法。通常的语法是for - in
  • 我会确保解决这个问题!谢谢

标签: ios swift parse-platform


【解决方案1】:

问题是您始终将这两个值保存在同一个 PFObject 实例中。

在循环中移动let spots = PFObject(className:"spot") 行。

PS:使用 Swift 原生类型。例如这样更有效

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

【讨论】:

  • 成功了,谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-06-30
  • 2016-05-18
  • 2016-05-05
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多