我有一个从CloudKit数据库获取的对象数组,它作为location()对象的数组返回。
location()定义为......
class location {
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D
}
我需要能够从数组中创建注释,但我似乎无法绕过它。
当我尝试将数组作为MKAnnotation传递时,它表示它不能正确地符合,虽然它确实具有符合所需的所有数据,但我无法弄清楚如何将它从数组中取出并且注释。
我的班级
class Locations: NSObject, MKAnnotation {
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D
override init()
{
self.title = "Test Title"
self.subtitle = "Test Subtitle"
self.coordinate = CLLocationCoordinate2D.init()
}
}
在我的视图控制器中创建“对象”...
var objects = [Locations]()
这是我用来从CK获取数据并将其存储在对象中的函数的一部分......
for locations in results! {
let newLocation = Locations()
newLocation.title = ckData["Name"] as? String
newHaunted.subtitle = ckData["Subtitle"] as? String
let location = ckData["Location"] as! CLLocation
self.objects.append(newLocation)
最后,我在ViewDidAppear中调用一个具有以下代码的函数...
let locationsToAdd = objects
mapView.showAnnotations(locationsToAdd, animated: true)
此时我从对象中获取一个空数组。如果我尝试使用Locations()而不是对象,则表示它无法将其转换为MKAnnotation,它应该已经存在。
以下是我用来从CloudKit获取数据的功能。
func getRecordsFromCloud() {
// Fetch data using Convenience API
let cloudContainer = CKContainer.defaultContainer()
let publicData = cloudContainer.publicCloudDatabase
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Locations", predicate: predicate)
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil { //no error
for locations in results! {
let newLocation = Locations()
newLocation.title = locations["Name"] as? String
newLocation.subtitle = locations["Subtitle"] as? String
let location = locations["Location"] as! CLLocation
let newLocationCoords: CLLocationCoordinate2D = location.coordinate
newLocation.coordinate = newLocation
self.objects.append(newHaunted)
dispatch_async(dispatch_get_main_queue(), {() -> Void in
self.locationsTable.reloadData()
})
}
}
else {
print(error)
}
}
}
在此之后,我在viewDidLoad中调用getRecordsFromCloud()。
答案 0 :(得分:1)
要指定您的班级符合某个协议,您必须使用class ClassName: ProtocolName
符号。因此,在您的情况下,您应该将class location
替换为class location: MKAnnotation
,以告诉编译器您的类符合MKAnnotation
协议。
答案 1 :(得分:1)
你可以使用@ Jelly的建议,或者只是声明你的类符合(实现)MKAnnotation
扩展名:
extension Location : MKAnnotation
{
}
答案 2 :(得分:0)
您可以像这样定义Location
类:
class Location: NSObject, MKAnnotation {
let title: String?
let subtitle: String?
var coordinate: CLLocationCoordinate2D
init(title: String?, subtitle: String?, coordinate: CLLocationCoordinate2D) {
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
super.init()
}
}
然后您可以像这样添加注释到地图:
let annotation = Location(title: name, subtitle: locality, coordinate: coordinate)
mapView.addAnnotation(annotation)
显然,您可以根据需要设置title
和subtitle
,但希望这可以说明这个想法。