I have looked at quite a few examples of using dispatch group but I can't seem to get it to work.
I am using Google Maps for my project, and have placed markers at nearby businesses. When a marker is clicked, I want to show another view controller which has images of the place.
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
self.loadPhotosForSalonByPlaceId(placeID: poiItem.placeId)
photoDispatchGroup.wait()
let salonInfoViewController = self.addPullUpController() //show view controller
salonInfoViewController.ImageCarouselView.images = self.salonImages
salonInfoViewController.salonName.text = poiItem.name
salonInfoViewController.salonAddress.text = poiItem.address
salonInfoViewController.openAppointmentSlotArray = self.openAppointmentSlots
self.isSalonInfoViewPresented = true
return isSalonInfoViewPresented
}
This is what my loadPhotosForSalonByPlaceId looks like:
func loadPhotosForSalonByPlaceId(placeID: String){
var countToLimitToFiveImages = 0
GMSPlacesClient.shared().lookUpPhotos(forPlaceID: placeID) { (photos, error) -> Void in
if let error = error {
// TODO: handle the error.
print("Error: \(error.localizedDescription)")
} else {
for photoMetadata in (photos?.results)! {
if countToLimitToFiveImages == 5 {
break;
}
self.photoDispatchGroup.enter()
self.loadImageForMetadata(photoMetadata: photoMetadata)
self.photoDispatchGroup.leave()
countToLimitToFiveImages += 1
}
}
}
}
Am I using the enter and leave incorrectly? Or should I be notifying the main thread to continue after the lookUpPhotos completes? Because right now, the array of UIImages is empty by the time I want to show the view controller.
Thanks in advance!
The code below is what I call in my loadPhotosForSalonByPlaceId function. It converts the PhotoMetaData into a UIImage, which I append to my array. From what I understand, the look up photos and the loadplacephoto are async calls. How can I go use DispatchGroup to show my view controller after both of these tasks are finished.
func loadImageForMetadata(photoMetadata: GMSPlacePhotoMetadata) {
var image = UIImage()
GMSPlacesClient.shared().loadPlacePhoto(photoMetadata, callback: {
(photo, error) -> Void in
if let error = error {
// TODO: handle the error.
print("Error: \(error.localizedDescription)")
} else {
image = photo!
self.salonImages.append(image)
}
})
}