Stc Stc - 2 months ago 16
Swift Question

Swift - "fatal error: unexpectedly found nil while unwrapping an Optional value" when trying to retrieve coordinates from Firebase

I have this error in my project. I get this error when I'm running the app. That I want to do Is show the position on the map bases on the coordinates that I have in my Firebase Database. But I get this error: fatal error: unexpectedly found nil while unwrapping an Optional value. I have googled around a bit but I don't find anything that would help me... And I'm pretty new in Swift and Xcode!

Here is my Firebase Database:

Firebase Database

And here Is my code:

class FeedCell: UICollectionViewCell, UICollectionViewDelegateFlowLayout, CLLocationManagerDelegate, MKMapViewDelegate {

let users = [User]()

var positions = [Position]()

var wiindow: UIWindow?
var mapView: MKMapView?
let locationManager = CLLocationManager()

let distanceSpan: Double = 500

var locationData: CLLocation!

override init(frame: CGRect) {
super.init(frame: frame)


required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")

let nameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFontOfSize(14)
label.translatesAutoresizingMaskIntoConstraints = false
return label

let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.cornerRadius = 22
imageView.layer.masksToBounds = true
imageView.backgroundColor = UIColor.blueColor()
return imageView

let separatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 192/255, green: 192/255, blue: 192/255, alpha: 1)
view.translatesAutoresizingMaskIntoConstraints = false
return view

func setupViews() {


addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[v0(44)]-10-[v1]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": profileImageView, "v1": nameLabel]))

addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[v0(44)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": profileImageView]))

addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v0]-385-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))

addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": separatorView]))

addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(1)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": separatorView]))

self.wiindow = UIWindow(frame: UIScreen.mainScreen().bounds)
self.backgroundColor = UIColor(white: 0.95, alpha: 1)

self.mapView = MKMapView(frame: CGRectMake(0, 70, (self.wiindow?.frame.width)!, 355))

self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.mapView!.showsUserLocation = true

self.mapView!.zoomEnabled = false
self.mapView!.scrollEnabled = false
self.mapView!.userInteractionEnabled = false


func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
if let mapView = self.mapView {
let region = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, self.distanceSpan, self.distanceSpan)
mapView.setRegion(region, animated: true)
mapView.showsUserLocation = true

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

FIRDatabase.database().reference().child("position").queryOrderedByChild("fromId").queryEqualToValue(FIRAuth.auth()!.currentUser!.uid).observeSingleEventOfType(.Value, withBlock: {(locationSnap) in

if let locationDict = locationSnap.value as? [String:AnyObject]{

self.locationData = locations.last

let lat = locationDict["latitude"] as! CLLocationDegrees //Here do I get the "Thread 1 EXC BAD INSTRUCTION"
let long = locationDict["longitude"] as! CLLocationDegrees
let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

self.mapView!.setRegion(region, animated: true)






That is because let lat = locationDict["latitude"] as! CLLocationDegrees fails. Wrap in in an guard let instead to make sure that you really have a value and if not handle it.

Something like this:

guard let lat = locationDict["latitude"] as? CLLocationDegrees,
      let long = locationDict["longitude"] as? CLLocationDegrees else { // Some error }