I have a UIViewController containing a MKMapView in Storyboard. Then I made an outlet of that mapview. From this screen I go to another screen where from a delegate is called back in the first viewcontroller which contains the map. Problem arises when in this delegate method, I try to get the mapview, it always gives me nil. Thus producing "unexpectedly found nil while unwrapping an Optional value”)" error.
Here is my code:
1)IBOutlet connection in MapViewController
@IBOutlet weak var map: MKMapView!
2) Delegate method in MapViewController:
func didSelectSearchContact(selectedContact: Contacts) -> Void{
let coordinate: CLLocationCoordinate2D = CLLocationCoordinate2DMake(selectedContact.lat, selectedContact.lng)
let span = MKCoordinateSpanMake(2.0, 2.0)
let region: MKCoordinateRegion = MKCoordinateRegion(center: coordinate, span: span)
print("self.map====== \(self.map)")
map.region = map.regionThatFits(region)//here comes the crash.
}
3) This is How the above delegate is being called from another view controller:
let contact = searchResults[indexPath.row] as! Contacts
self.delegate = MapViewController()
self.delegate?.didSelectSearchContact(contact)
Let me know what I'm doing wrong here!! Thanks!