jeudi 1 janvier 2015

Has anyone fixed a crash with the mapkit?

I am new to programming, so if this is a simple question, please forgive me.


I am getting the following error in my console when my app tries to launch the location function:


fatal error: unexpectedly found nil while unwrapping an Optional value


I'm not sure what it means, or how to fix it. This is the line of code it highlights when it crashes:



var latitude: Double = location.coordinate.latitude


My full code is as follows: import UIKit import CoreLocation import MapKit


class LocationController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {



let locationManager = CLLocationManager()


@IBOutlet var theMap: MKMapView!


var manager:CLLocationManager!
var myLocations: [CLLocation] = []


override func viewDidLoad()
{
super.viewDidLoad()

self.theMap.mapType = MKMapType.Standard
self.theMap.showsUserLocation = true

//self.theMap.removeAnnotations(self.theMap.annotations)





locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()


let location = self.locationManager.location

var latitude: Double = location.coordinate.latitude
var longitude: Double = location.coordinate.longitude

println("current latitude :: \(latitude)")
println("current longitude :: \(longitude)")



}

override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()

}


//You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
//-

let location = locations.last as CLLocation

let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))


self.theMap.setRegion(region, animated: true)


// Add an annotation on Map View
var point: MKPointAnnotation! = MKPointAnnotation()

point.coordinate = location.coordinate
point.title = "Current Location"
point.subtitle = "sub title"

self.theMap.addAnnotation(point)

//stop updating location to save battery life
locationManager.stopUpdatingLocation()

}






func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!
{
if !(annotation is MKPointAnnotation)
{
return nil
}

let reuseId = "test"

var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)

if anView == nil
{
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.image = UIImage(named:"1.png")
anView.canShowCallout = true
}
else
{
anView.annotation = annotation
}

return anView
}




}


Does anyone have a suggestion on how I can fix this error?




Aucun commentaire:

Enregistrer un commentaire