The download restaurant function returns 2, so it's not an issue of an empty array. However, as I try to take each value in the array and put it through my for loop to add an annotation to the map, nothing happens. No print statement, no annotations. I have a print statement in my current loop and it did not run, but I am unsure why it is not running.
I tried putting the for loop in its own function and placing it after the download fuction but no difference.
I'm including the entire code to best provide all the information regarding this issue
import UIKit
import CloudKit
import SafariServices
import MapKit
import GoogleMobileAds
class InterFood: UIViewController, MKMapViewDelegate {
@IBOutlet weak var myMap: MKMapView!
var bannerView: GADBannerView!
var restaurantArray: Array<CKRecord> = []
var index: NSIndexPath!
var pin: AnnotationPin!
override func viewDidLoad() {
super.viewDidLoad()
print("Hi")
self.myMap.delegate = self
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)
func downloadRestaurants () {
let publicDB = CKContainer.default().publicCloudDatabase
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "InternationalCenter", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "Name", ascending: true)]
publicDB.perform(query, inZoneWith: nil) { (results, error) -> Void in
if (error != nil) {
print("Error" + (error?.localizedDescription)!)
} else {
for result in results! {
self.restaurantArray.append(result)
}
OperationQueue.main.addOperation( { () -> Void in
self.myMap.reloadInputViews()
// activityIndicator.isHidden = true
print("Downloading")
print(self.restaurantArray.count)
})
}
}
}
downloadRestaurants()
print("Hi Again")
self.title = "International Center"
let coordinate = CLLocationCoordinate2D(latitude: 42.722869, longitude: -84.488012)
let region = MKCoordinateRegionMakeWithDistance(coordinate, 2000, 2000)
myMap.setRegion(region, animated: true)
for res in restaurantArray {
pin = AnnotationPin(title: res.value(forKey: "Name") as! String, subtitle: "Address", theCoordinates: res.value(forKey: "Location") as! CLLocationCoordinate2D, theWeb: "https://google.com")
myMap.addAnnotation(pin)
self.myMap.reloadInputViews()
}
}
}
I've tried implementing this function described here but no success as our code is quite similar: how to set up array for multi annotations with swift
The reason the restaurantArray is empty when you iterate over it is because the query is performed asynchronously. viewDidLoad()
will execute in it's entirety before your query returns results. You can see this in the output of your program. It prints "Hi Again" before "Downloading" even though you call downloadRestaurants()
first.