2015-03-15 3 views
3

У меня проблема, потому что мое приложение падает, когда я пытаюсь получить позицию пользователя и имею разрешение на мой .plist этот мой код.CLLocationManager фатальная ошибка: неожиданно найден nil во время разворачивания необязательного значения Swift

import UIKit 
import MapKit 
import CoreLocation 

class mapClass : UIViewController,MKMapViewDelegate,CLLocationManagerDelegate{ 

    var location4 = CLLocation() 
    var lm = CLLocationManager() 

    @IBOutlet var propMapa: MKMapView! 

    lm.delegate=self 
    lm.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
    lm.distanceFilter = kCLDistanceFilterNone 
    lm.startUpdatingLocation() 

    println("\(lm.location)") <---- nil 

    location4 = lm.location <---- crash 

} 

Log: фатальная ошибка: неожиданно нашел ноль в то время как разворачивание необязательного значения

ответ

6

После вызова lm.startUpdatingLocation() менеджер местоположения вызывает didUpdateLocations() всякий раз, когда он обнаруживает изменения местоположения, так что вам нужно реализовать CLLocationManager::didUpdateLocations, чтобы получить расположение:

import UIKit 
import MapKit 
import CoreLocation 

class mapClass : UIViewController,MKMapViewDelegate,CLLocationManagerDelegate{ 

    var location4 = CLLocation() 
    var lm = CLLocationManager() 

    @IBOutlet var propMapa: MKMapView! 

    ... 

    lm.delegate=self 
    lm.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
    lm.distanceFilter = kCLDistanceFilterNone 
    lm.startUpdatingLocation() 
} 

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

    let currentLocation = locations.last as CLLocation 
    println(currentLocation) 
    ... 
} 
+0

Благодаря это работает отлично. – Fabio

0
import UIKit 
import MapKit 
import CoreLocation 
class ViewController: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate 
{ 
    @IBOutlet weak var mapView: MKMapView! 
    @IBOutlet weak var textField: UITextField! 
    @IBOutlet weak var searchButton: UIButton! 
    let locationManager = CLLocationManager() 
    var location:CLLocationCoordinate2D! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     println("Search Button Clicked"); 
     mapView.showsUserLocation = true; 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    @IBAction func searchButtonClicked(sender:AnyObject) 
    { 
     locationManager.distanceFilter = kCLDistanceFilterNone 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.delegate = self 

     locationManager.requestWhenInUseAuthorization() 

     locationManager.startUpdatingLocation() 
    } 

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

     println("delegate called") 
     if manager.location != nil 
     { 
      println(locationManager.location.coordinate.latitude) 
      let artwork = Artwork(title: "Ram", 
       locationName: "Infotech", 
       discipline: "Testing", 
       coordinate: CLLocationCoordinate2D(latitude:manager.location.coordinate.latitude, longitude:manager.location.coordinate.longitude)) 

      mapView.addAnnotation(artwork) 
     } 

    } 

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) 
    { 

     println(error) 
    } 
} 
Смежные вопросы

 Смежные вопросы