为什么在我的QueryOperation中“自我”阻止来自CloudKit的数据

时间:2017-12-19 08:07:40

标签: ios swift mapkit cloudkit

我在Cloudkit的数据库中有多个CKRecords。我将这些CKRecords转换为我的地图注释。自从我在我的查询操作中在变量self之前添加var annotation = MKPointAnnotation()之后,它只将一个注释加载到我的Map中。为什么这样,我该如何解决?任何帮助都会很棒!

我如何获取记录 -

 var points: [MKPointAnnotation] = []
 var annotation = MKPointAnnotation()
 let database = CKContainer.default().publicCloudDatabase

 func fetchTruck() {

let truePredicate = NSPredicate(value: true)
let eventQuery = CKQuery(recordType: "User", predicate: truePredicate)
let queryOperation = CKQueryOperation(query: eventQuery)


queryOperation.recordFetchedBlock = {  (record) in



    self.points.append(self.annotation)

    self.annotation.title = record["username"] as? String
    self.annotation.subtitle = record["hours"] as? String
    if let location = record["location"] as? CLLocation {
        self.annotation.coordinate = location.coordinate
    }

    print("recordFetchedBlock: \(record)")

    self.mapView.addAnnotation(self.annotation)

    }




        self.database.add(queryOperation)

}

1 个答案:

答案 0 :(得分:1)

在详细查看您的代码后,我认为问题在于您使用的是相同的注释。 MKPointAnnotation是一个类,一个参考值,这意味着每次你为self.annotation赋值时,你都在改变引用,而不是创建一个新引用。

您正在修改CKQueryOperation关闭内的应用UI(mapView)。尝试在主线程中运行修改代码

尝试类似......

var points: [MKPointAnnotation] = []
let database = CKContainer.default().publicCloudDatabase

func fetchTruck() 
{
    let truePredicate = NSPredicate(value: true)

    let eventQuery = CKQuery(recordType: "User", predicate: truePredicate)
    let queryOperation = CKQueryOperation(query: eventQuery)

    queryOperation.recordFetchedBlock = {  (record) in
        var annotation = MKPointAnnotation()

        annotation.title = record["username"] as? String
        annotation.subtitle = record["hours"] as? String
        if let location = record["location"] as? CLLocation 
        {
            annotation.coordinate = location.coordinate
        }

        self.points.append(annotation)

        DispatchQueue.main.async
        {
            self.mapView.addAnnotation(annotation)
        }

        print("recordFetchedBlock: \(record)")
    }

    self.database.add(queryOperation)
}