0

So I am going through project 19 learning how to drop the pins on a map. I have basically gotten to the point where I have the exact same thing the author has in my viewController.swift file and my Capital.swift files. The app will build successfully however it will crash once it gets to the following section saying that there is a fatal error: unexpectedly found nil while unwrapping an Optional value mapView.addAnnotation(london) mapView.addAnnotation(oslo) mapView.addAnnotation(paris) mapView.addAnnotation(rome) mapView.addAnnotation(washington) This is my entire ViewController.swift file

import UIKit import MapKit
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let london = Capital(title: "London", coordinate: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), info: "Home to the 2012 Summer Olympics.")
    let oslo = Capital(title: "Oslo", coordinate: CLLocationCoordinate2D(latitude: 59.95, longitude: 10.75), info: "Founded over a thousand years ago.")
    let paris = Capital(title: "Paris", coordinate: CLLocationCoordinate2D(latitude: 48.8567, longitude: 2.3508), info: "Often called the City of Light.")
    let rome = Capital(title: "Rome", coordinate: CLLocationCoordinate2D(latitude: 41.9, longitude: 12.5), info: "Has a whole country inside it.")
    let washington = Capital(title: "Washington DC", coordinate: CLLocationCoordinate2D(latitude: 38.895111, longitude: -77.036667), info: "Named after George himself.")

    mapView.addAnnotation(london)
    mapView.addAnnotation(oslo)
    mapView.addAnnotation(paris)
    mapView.addAnnotation(rome)
    mapView.addAnnotation(washington)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

Sorry if this is overkill and if there is an easier way to show the problem please let me know. Any and all help is appreciated. Thank you!

1 Answers1

0

First of all, as suggested in the comments, have you connected your IBOutlet in your storyboard?

If you have, try this:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    mapView.addAnnotation(london)
    mapView.addAnnotation(oslo)
    mapView.addAnnotation(paris)
    mapView.addAnnotation(rome)
    mapView.addAnnotation(washington)
}

and delete the mapView.addAnnotation() from your viewDidLoad

Ocunidee
  • 1,769
  • 18
  • 20