Reputation: 59
after much researching i think i have found the problem of my coding.
I am trying to setup a app where users can see their locations after where they are.
I always get an error which says
fatal error unexpectedly found nil while unwrapping an optional value (lldb)
And the error is showed as Thread 1: EXC_BAD_INSTRUCTION at this line:
self.mapView.showsUserLocation = true
When i try to delete the line the exact same error shows up on another .mapView. So the error appears at everyline where i have used my mapkit and IBAOutlet(mapView).
I can't seem to figure out what the problem is. When i propertied the mapkit i went to the Main.Storyboard -> CTR + drag -> ViewController.swift and called it "mapView"
Thank you for your time
Here is all of my codes
import UIKit
import Parse
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Location Delegate Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error:" + error.localizedDescription)
}
}
Upvotes: 2
Views: 2459
Reputation: 4596
It seems to be a timing (or interface builder hookup) problem.
To avoid this, try changing the type of the outlet to MKMapView?
and use optional coalesking like so:
self.mapView?.showsUserLocation = true
This at least takes care of the timing problem leading to a crash so you can pinpoint the problem more accurately.
If after the crash no map view is showing up, it might not be a timing but a interface builder hookup problem. Make sure you connected the map view to the outlet then.
Upvotes: 1
Reputation: 9855
Remove the "weak" from the var MapView. If you hold no strong reference the outlet will be de-allocated immediately.
Upvotes: 0