I need to display a photo for a group of annotations (cluster) on a map. The photo should be selected randomly from the annotations that are inside that cluster. Currently, my method only works if I assign a static variable for 'pinToDisplay' in the 'AllPins' class. However, this causes a memory leak when a lot of pins are added, since it stores the photo from Firebase data. If I remove the static property from the variable, memory usage becomes more efficient, but the cluster is unable to display a photo for a group of annotations. It still works for a single annotation though. here the code
class PinParsed: Codable {
let createdDate, id, owner, updatedDate: String?
let address: String?
let approve: Bool?
let category: [String]?
let city: String?
let country: String?
let creator: String?
let image: String?
let img: String?
let lat: String?
let linkPinAll: String?
let linkPinTitle, long: String?
let subscrtag: [String]?
let title: String?
let gal: [GalClass]?
let instagramLink, googleStreetViewURL: String?
}
class PinAnnotation : MKPointAnnotation {
var pin: PinParsed!
var image: String!
}
final class AllPins {
static var pinToDisplay: [PinAnnotation]?
deinit {
print("allpins deinit")
}
//This is in the class which is responsible for cluster
override var annotation: MKAnnotation? {
didSet {
guard let annotation = annotation as? MKClusterAnnotation else {
return
}
countLabel.text = "\(annotation.memberAnnotations.count)"
}
willSet {
guard let annotation = annotation as? MKClusterAnnotation else {
return
}
var randomElement = annotation.memberAnnotations.randomElement()
let latitude = randomElement?.coordinate.latitude
let longitude = randomElement?.coordinate.longitude
if latitude != nil, longitude != nil {
if let allPins = AllPins.pinToDisplay {
allPins.forEach { pinAnnotation in
if pinAnnotation.coordinate.latitude == latitude && pinAnnotation.coordinate.longitude == longitude {
if let url = URL(string: pinAnnotation.pin.img!) {
URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
if let error = error {
print(error.localizedDescription, "cluster photo")
}
if let imageData = data {
DispatchQueue.main.async {
self!.imageView.image = UIImage(data: imageData)
self!.imageView.contentMode = .scaleAspectFill
}
}
}.resume()
}
}
}
}
}
}