-2

Below is my code to placing an annotation on a Map View. I'm getting a "unexpectedly found nil while unwrapping optional value error". I do not know why my annotation value is giving a nil value.

    import UIKit
import MapKit

class MapViewcontroller: UIViewController {

    var itemStore: ItemStore!
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        print("test")

        let annotation = MKPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: 40.71304, longitude: -74.0072)
        annotation.title = "Test"
        self.mapView.addAnnotation(annotation) //error here
    }
Luke Noel
  • 1
  • 2

1 Answers1

0

Probably annotation is ok, just check that you had connected @IBOutlet weak var mapView: MKMapView! with storyboard object.

Vasilii Muravev
  • 3,063
  • 17
  • 45
  • Why do I need to connect it with a storyboard object? I'm just loading it on the load of the view. – Luke Noel Jul 13 '17 at 16:53
  • @LukeNoel cuz you're using `@IBOutlet`. If you don't use Storyboard, then make you `MKMapView` programmatically. – Vasilii Muravev Jul 13 '17 at 16:54
  • @LukeNoel Where do you expect the `MKMapView` object to be created from? All you have is an empty reference. Either you have to instantiate it yourself, or hook it up to a story board that will instantiate it for you – Alexander Jul 13 '17 at 17:03