我有一个功能,可以根据用户的当前位置显示MKMapView上的引脚。此功能利用了GeoFire的GFQuery:
// Allows the user to scroll on the map and have the parties update
func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
let loc = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude)
showPartiesOnMap(location: loc)
}
从代码片段中可以看到,此函数在地图上重复调用showParties(每次更新位置)。该函数如下所示:
func showPartiesOnMap(location:CLLocation) {
circleQuery = geoFire?.query(at: location, withRadius: 2.5)
// Observe whenever we find a sighting. If there are 50 parties, this will be called 50 times
partyObserve = circleQuery?.observe(GFEventType.keyEntered, with: { (key, location) in
if let location = location, let key = key {
let anno: PartyAnnotation
self.fullPartyName = key
// Attempting to print just the name of the party and not the time
var characters = Array(key.characters)
var currentChar: Character = " "
var finalName: String = ""
var dateString: String = ""
var finalDate: Date? = nil
// Gets the name of the party
currentChar = characters.remove(at: 0)
while currentChar != "*" {
finalName += "\(currentChar)"
currentChar = characters.remove(at: 0)
}
// Gets the date the party was created
currentChar = characters.remove(at: 0)
while currentChar != "*" {
dateString += "\(currentChar)"
currentChar = characters.remove(at: 0)
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
finalDate = dateFormatter.date(from: dateString)!
// Check if the party should still exist
if(self.shouldBeDeleted(partyDate: finalDate!)) {
self.geoFire.removeKey(key)
}
else if characters.count > 0 {
// The party in question is public
}
else {
// Created an annotation because the party should not be deleted
anno = PartyAnnotation(coordinate: location.coordinate, partyName: finalName)
self.mapView.addAnnotation(anno)
}
}
})
}
我面临的问题是,当用户离开此页面时,我将无法再正确观察Firebase上的任何内容。对于以后的任何观察(非GeoFire),我在展开一个可选值时都会收到意外发现的nil。
经过一堆测试,我得出的结论是问题出在线路上:
partyObserve = circleQuery?.observe(GFEventType.keyEntered, with: { (key, location) in
如果我注释掉该观察结果,则不会发生此问题。不幸的是,我需要此功能,因此将其注释掉不是可行的解决方案。我试图删除AllObservers并使用Firebase Handles删除观察值。有谁知道为什么会发生这种情况或可能的解决方案?
预先感谢您的帮助!