我只是想注释添加到我的地图的看法,但我一直运行到这个错误“意外发现零,同时展开”,我似乎无法来解决这个问题或发现在我的情况下,有效的解决方案。可能有人请告诉我在哪里出了问题。提前致谢。我已经尝试改变var mapView: MKMapView!
没有成功var mapView: MKMapView?
class customPin: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(pinTitle:String, pinSubTitle:String, location:CLLocationCoordinate2D) {
self.title = pinTitle
self.subtitle = pinSubTitle
self.coordinate = location
}
}
var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
let location = CLLocationCoordinate2D(latitude: 32.2325, longitude:76.3242)
let region = MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))
self.mapView.setRegion(region, animated: true)
let pin = customPin(pinTitle: "Honory Dalailama Temple", pinSubTitle: "Dharamshala, Himachal Pradesh, India", location: location)
self.mapView.addAnnotation(pin)
self.mapView.delegate = self
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "customannotation")
annotationView.image = UIImage(named:"pin")
annotationView.canShowCallout = true
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
print("annotation title == \(String(describing: view.annotation?.title!))")
}
fileprivate func setupLocationManager() {self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() == true {
if CLLocationManager.authorizationStatus() == .restricted || CLLocationManager.authorizationStatus() == .denied || CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
locationManager.desiredAccuracy = 1.0
locationManager.delegate = self
locationManager.startUpdatingLocation()
} else {
print("PLease turn on location services or GPS")
}
}
fileprivate func setupMapView() {
let mView = MKMapView(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height))
mView.showsUserLocation = true
view.addSubview(mView)
mView.showsScale = true
mView.showsPointsOfInterest = true
mView.showsTraffic = true
mView.showsCompass = true
mView.userTrackingMode = .follow
self.mapView = mView
}
}
这看起来车:
print("annotation title == \(String(describing: view.annotation?.title!))")
如果annotation
是零,你力!
展开它,这将导致该崩溃。
改用:
print("annotation title == \(String(describing: view.annotation?.title))")
这也不清楚,你已经叫setupMapView()
和实际设置mapView
被调用之前viewDidLoad()
。在viewDidLoad()
添加一行:
if mapView == nil { setupMapView() }
使用前mapView
。