2016-09-04 29 views
1

所以我有一個問題,我把一些物品放在一個對象後調用保存。我去了一個API,我下載了一些信息,然後將它保存到另一個系統以供臨時使用,但是.save()似乎只保存了2個項目,沒有特殊的模式。有人可以解釋什麼是問題嗎?保存在一個while循環快速解析

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

什麼是'HotSpots'?附註:'當我<<...'並且遞增計數器在Swift中是非常糟糕的語法。通常的語法是「for-in」。 – vadian

+0

我會確保解決這個問題!謝謝 –

回答

2

的問題是,你是在同一個PFObject實例始終保存兩個值。

在循環中移動線let spots = PFObject(className:"spot")。 PS:使用Swift本機類型。例如這是更高效的

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

這樣做,謝謝! –