我正在设计 myCurrentLocationBtn
并在关闭地理定位时在 let center
出现错误
@IBAction func CurrentLocation(sender: AnyObject) {
let Authflag = CLAuthorizationStatus.self
print(Authflag)
let userLocation = locationmanager.location
let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)
var currentAnnotation = MKPointAnnotation()
currentAnnotation.coordinate = center
currentAnnotation.title = "You're here!"
MapApple.addAnnotation(currentAnnotation)
}
错误是fatal error: expectedly found nil while unwrapping an Optional value
我该如何解决?
禁用地理定位这样的功能
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
locationmanager.stopUpdatingLocation()
print (error)
}
错误此 Error Domain=kCLErrorDomain Code=0 "(null)"
最佳答案
只需使用 guard 来确保它不是 nil:
@IBAction func CurrentLocation(sender: AnyObject) {
let Authflag = CLAuthorizationStatus.self
print(Authflag)
guard let userLocation = locationmanager.location else {
//tell the user that an error occurred
return
}
let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
var currentAnnotation = MKPointAnnotation()
currentAnnotation.coordinate = center
currentAnnotation.title = "You're here!"
MapApple.addAnnotation(currentAnnotation)
}
关于ios - 应用程序取消并出现 fatal error : unexpectedly found nil while unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33997568/