2016-11-27 60 views
0

我在CloudKit中將座標定位爲位置數據類型(「Koordinaatit」)。我試圖繪製MKPointAnnotation從這些座標映射,但我不知道如何從數組獲取座標到註釋。從CloudKit到MKPointAnnotation的座標

var sijainnitArray:[CKRecord] = [] 


    func drawPin(sijainti: Int) { 

     let annotation = MKPointAnnotation() 
     annotation.coordinate = CLLocationCoordinate2D(sijainnitArray[sijainti].Koordinaatit) //XCode shows error: Value of type 'CKRecord' has no memeber 'Koordinaatit' 
     self.mapView.addAnnotation(annotation) 
} 


func fetchRecordsFromCloud() { 

     let cloudContainer = CKContainer.default() 
     let publicDatabase = cloudContainer.publicCloudDatabase 
     let predicate = NSPredicate(value: true) 
     let query = CKQuery(recordType: "Sijainti", predicate: predicate) 

     publicDatabase.perform(query, inZoneWith: nil, completionHandler: { 
      (results, error) -> Void in 

      if error != nil { 
       print(error) 
       return 
      } 

      if let results = results { 
       print("Completed the download of locations data") 
       self.sijainnitArray = results 
       } 
     }) 

    } 



override func viewDidLoad() { 
    super.viewDidLoad() 

    fetchRecordsFromCloud() 

    let sijainnitLkm = sijainnitArray.count - 1 

    for i in 0...sijainnitLkm { 
     drawPin(sijainti: i) 
     } 
} 



**ANSWER** 

let sijaintilista = self.sijainnitArray[i] 

      let sijaintiLatLong = sijaintilista.object(forKey: "Koordinaatit") as? CLLocation 
      let sijaintiLat = sijaintiLatLong?.coordinate.latitude 
      let sijaintiLon = sijaintiLatLong?.coordinate.longitude 

      let sourceLocation = CLLocationCoordinate2D(latitude: sijaintiLat!, longitude: sijaintiLon!) 
      let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil) 

      if let location = sourcePlacemark.location { 
       annotation.coordinate = location.coordinate 
      } 

      self.mapView.addAnnotation(annotation) 

回答

0

您要使用的方法object(forKey:)CKRecord。大概你想用的鑰匙是「Koordinaatit」。

我以前沒有用過CloudKit。看起來您可以直接將CLLocation保存到CKRecord

+0

在locationManager中將位置保存爲CloudKit CKRecord作爲CLLocation,問題是我不知道如何將CLLocation添加到MKPointAnnotation。 let location = locations.last! 讓publicDatabase = CKContainer.default()publicCloudDatabase 讓記錄= CKRecord(RECORDTYPE: 「Sijainti」)。 record.setObject(位置,forKey: 「Koordinaatit」) publicDatabase.save(記錄,completionHandler:{ (記錄,錯誤) - >在 – Erva

+0

無效好吧,所以你需要使用'object(forKey:)'從cloudKit讀取記錄,然後將其轉換爲'CLLocation' –

+0

爲我的答案增加了解決方案。 – Erva