У меня есть эта ошибка в моем проекте. Я получаю эту ошибку, когда запускаю приложение. Это я хочу показать. Показывает позицию на основах карты в координатах, которые у меня есть в моей базе данных Firebase. Но я получаю эту ошибку: фатальная ошибка: неожиданно найден nil при развертывании необязательного значения. Я немного погубил, но я не нашел ничего, что могло бы помочь мне ... И я довольно новый в Swift и Xcode!Swift - «фатальная ошибка: неожиданно обнаружена нуль при развертывании необязательного значения» при попытке получить координаты из Firebase
Вот мой Firebase База данных:
А вот мой код:
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)
setupViews()
}
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() {
addSubview(profileImageView)
addSubview(nameLabel)
addSubview(separatorView)
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.addSubview(self.mapView!)
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
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)
self.locationManager.stopUpdatingLocation()
}
})
}
}
Взгляните на то, что 'locationDict [ "широта"]' есть. Вы принудительно развертываете его как 'CLLocationDegrees'. В идеале вы никогда не должны форсировать разворот, каждое появление! вы должны быть удалены. –
См. Http://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1, чтобы узнать, как отладить сбой. – rmaddy
Хорошо, спасибо за информацию! Очень ценю это, и я обязательно прочитаю статью! – Stc