Ios Swift MKMapView有时会变为零,应用程序崩溃
我正在显示这样的地图:Ios Swift MKMapView有时会变为零,应用程序崩溃,ios,swift,mkmapview,mapkit,Ios,Swift,Mkmapview,Mapkit,我正在显示这样的地图: //Map @IBOutlet var mapView: MKMapView! var location: String? override func viewDidLoad() { super.viewDidLoad() self.mapView.delegate = self if let location = location { let address = lo
//Map
@IBOutlet var mapView: MKMapView!
var location: String?
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
if let location = location {
let address = location
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
if let placemarks = placemarks {
if placemarks.count != 0 {
let annotation = MKPlacemark(placemark: placemarks.first!)
self.mapView.addAnnotation(annotation)
let span = MKCoordinateSpanMake(0.1, 0.1)
let region = MKCoordinateRegionMake(annotation.coordinate, span)
self.mapView.setRegion(region, animated: false)
}
}
}
}
}
//Fixing map memory issue
override func viewWillDisappear(_ animated:Bool){
super.viewWillDisappear(animated)
self.applyMapViewMemoryFix()
}
//Fixing map memory issue
func applyMapViewMemoryFix(){
switch (self.mapView.mapType) {
case MKMapType.hybrid:
self.mapView.mapType = MKMapType.standard
break;
case MKMapType.standard:
self.mapView.mapType = MKMapType.hybrid
break;
default:
break;
}
self.mapView.showsUserLocation = false
self.mapView.delegate = nil
self.mapView.removeFromSuperview()
self.mapView = nil
}
如果我退出VC,再快速返回几次,应用程序最终会崩溃,因为MKMapView变为零
崩溃发生在self.mapView.addAnnotation(annotation)
我不知道为什么,但我猜是
geocoder.geocodeAddressString
还没有完成加载/搜索,如果我足够快地退出VCmapView
将变为nil你将self.mapView
设置为nil
你的视图将消失方法。因此,只要你在地理编码器完成之前离开视图控制器,你的应用程序就会崩溃
只需在geocoder块中添加对nil
的适当检查
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
if let location = location {
let address = location
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
if let placemarks = placemarks {
if placemarks.count != 0 {
if let mapView = self.mapView {
let annotation = MKPlacemark(placemark: placemarks.first!)
mapView.addAnnotation(annotation)
let span = MKCoordinateSpanMake(0.1, 0.1)
let region = MKCoordinateRegionMake(annotation.coordinate, span)
mapView.setRegion(region, animated: false)
}
}
}
}
}
}