我只是想在我的地图视图中添加注释,但是我一直遇到这个错误“在解包时意外地发现了零”,而且我似乎无法解决它,也找不到适合我的解决方案。有人能告诉我哪里出了问题吗?事先谢谢。我已经试过将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
之前。
关于swift - Swift 4添加注释错误意外地在展开时发现了nil,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54565895/