I have coordinates in CloudKit as Location data type ("Koordinaatit"). I'am trying to draw MKPointAnnotation to map from these coordinates but i don't know how to get coordinates from array to annotation.
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)
You want to use the method object(forKey:)
on your CKRecord
. Presumably the key you want to use is "Koordinaatit".
I haven't used CloudKit before. It looks like you can save a CLLocation directly into a CKRecord
.