我试图让应用程序找到用户的位置,一旦应用程序已经启动。但是,当我尝试使用viewDidLoad方法并接收到以下错误时,我不断地在requestWhenInUseAuthorization方法中发现一个错误:
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)如果有人能帮我找到解决这个问题的办法,我将非常感激。谢谢!
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var lastLocation = CLLocation()
var locationAuthorizationStatus:CLAuthorizationStatus!
var window: UIWindow?
let locationManager: CLLocationManager!
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.initLocationManager()
}
override func viewDidLoad() {
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled()) {
seenError = false
locationFixAchieved = false
locationManager = CLLocationManager()
self.initLocationManager()
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
mapView.showsUserLocation = true
mapView.delegate = self
self.mapView.setUserTrackingMode(MKUserTrackingMode.Follow, animated: true);
}
// Location Manager helper stuff
func initLocationManager() {
locationManager.requestWhenInUseAuthorization()
}
// Location Manager Delegate stuff
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
if ((error) != nil) {
if (seenError == false) {
seenError = true
print(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}}
发布于 2015-02-27 17:02:23
在didAppear方法之前调用的是didload方法。因此,您的位置管理器尚未初始化。因此,您需要在使用它之前初始化它。
https://stackoverflow.com/questions/28769848
复制相似问题