マップビューに注釈を追加しようとしていますが、「アンラップ中に予期せずnilが見つかりました」というエラーが発生し続け、解決できないか、私の場合に機能する解決策を見つけることができません。誰かが私がどこで間違っているのか教えてもらえますか?前もって感謝します。私はすでにに変更しようと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
がnilの場合は、強制的にラップを解除して!
いるため、クラッシュが発生します。
代わりに使用してください:
print("annotation title == \(String(describing: view.annotation?.title))")
また、以前に呼び出しsetupMapView()
て実際に設定したことが呼び出されるかどうかも明確ではありません。次の行を追加します。mapView
viewDidLoad()
viewDidLoad()
if mapView == nil { setupMapView() }
使用する前にmapView
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加