Аннотации Mapview не отображаются после загрузки из базы данных cloudkit publi c - PullRequest
0 голосов
/ 04 августа 2020

У меня есть IBOutlet mapView. Я пытаюсь получить 3 «корзины» из моей базы данных iCloud publi c и в viewDidLoad организовать их в отдельные массивы, чтобы отдельно отображать аннотации (у меня есть система фильтрации для отображения определенного типа бункеры.) Мне уже удалось получить и отобразить эту информацию в табличном представлении, но по какой-то причине количество извлеченных бункеров в этом контроллере представления равно нулю, и 3 аннотации не отображаются. Вот оно внизу.

@IBOutlet var mapView: MKMapView!

var bins: [CKRecord] = []

//types of bins
var clothingAnnotations: [MKAnnotation] = []
var toysAnnotations: [MKAnnotation] = []
var metalAnnotations: [MKAnnotation] = []
var otherAnnotations: [MKAnnotation] = []
    
//filtering system checkboxes
@IBOutlet var clothingBox: UIButton!
@IBOutlet var toysBox: UIButton!
@IBOutlet var metalBox: UIButton!
@IBOutlet var otherBox: UIButton!


   override func viewDidLoad() {
    super.viewDidLoad()
    fetchRecordsFromCloud()
    mapView.showsCompass = true
    mapView.showsScale = true
    mapView.showsTraffic = true
    
    mapView.delegate = self

    for bin in bins {

        
        let geoCoder = CLGeocoder()
        //geocode the "address" field of the fetched record
        geoCoder.geocodeAddressString(bin.object(forKey: "address") as? String ?? "", completionHandler: {
                placemarks, error in
            if let error = error {
                print(error)
                return
            }

    
            if let placemarks = placemarks {
            // Get the first placemark
                let placemark = placemarks[0]

                let annotation = MKPointAnnotation()
                annotation.title = bin.object(forKey: "type") as? String
                
                
                if let location = placemark.location {
                    annotation.coordinate = location.coordinate
                    //organize into arrays above
                    if annotation.title == "Clothing"{
                            self.clothingAnnotations.append(annotation)
                        }else if annotation.title == "Toys"{
                            self.toysAnnotations.append(annotation)
                        }else if annotation.title == "Metal"{
                            self.metalAnnotations.append(annotation)
                        }else if annotation.title == "Other"{
                            self.otherAnnotations.append(annotation)
                        }
                        self.mapView.selectAnnotation(annotation, animated: true)
                        
                
                        }
                    }
            
                }
                )
        
        }
    }
func fetchRecordsFromCloud() {
    // Fetch data using Convenience API
    let cloudContainer = CKContainer.default()
    let publicDatabase = cloudContainer.publicCloudDatabase
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "Bins", predicate: predicate)
    print(query.recordType)
    print(publicDatabase.databaseScope)
    

    publicDatabase.perform(query, inZoneWith: nil, completionHandler: {
        (results, error) -> Void in
        if let error = error {
            print(error)
            return
        }
        if let results = results{
            print(results.count) //prints zero
            print("download complete")
            self.bins = results
        }
    })
}


//the following functions are for the filtering system
@IBAction func clothingBoxTapped(_ sender: UIButton) {
    if clothingBox.isSelected{
        clothingBox.isSelected = false
        self.mapView.removeAnnotations(clothingAnnotations)
    }else{
        clothingBox.isSelected = true
        self.mapView.showAnnotations(clothingAnnotations, animated: false)
    }
}
@IBAction func toysBoxTapped(_ sender: UIButton) {
    if toysBox.isSelected{
        toysBox.isSelected = false
        self.mapView.removeAnnotations(toysAnnotations)
    }else{
        toysBox.isSelected = true
        self.mapView.showAnnotations(toysAnnotations, animated: false)
    }
}
@IBAction func metalBoxTapped(_ sender: UIButton) {
    if metalBox.isSelected{
        metalBox.isSelected = false
        self.mapView.removeAnnotations(metalAnnotations)
    }else{
        metalBox.isSelected = true
        self.mapView.showAnnotations(metalAnnotations, animated: false)
    }
}
@IBAction func otherBoxTapped(_ sender: UIButton) {
    if otherBox.isSelected{
        otherBox.isSelected = false
        self.mapView.removeAnnotations(otherAnnotations)
    }else{
        otherBox.isSelected = true
        self.mapView.showAnnotations(otherAnnotations, animated: false)
    }
}

Я уже давно пытался в этом разобраться. Есть ли у кого-нибудь подсказки или замечал что-то не так?

...