And*_*alz 1 iphone optional ios swift ios8
我目前有一个测试应用程序来自学Core Location.这是一个带有按钮的应用程序,可以在按下按钮时显示您的位置,也可以在位置服务关闭时显示警报.
我得到一个致命的错误(在解包选项值时意外地发现nil)当位置服务打开并且我尝试打印字符串时.我在文档中找不到CLLocationManager.location.coordinate返回可选值的任何地方.我将包含代码段.谢谢!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.authorizationStatus() == .NotDetermined {
locationManager.requestWhenInUseAuthorization()
}
}
@IBAction func testLocation(sender: AnyObject) {
switch CLLocationManager.authorizationStatus() {
case .AuthorizedAlways, .AuthorizedWhenInUse:
printCurrentCoordinates()
case .Restricted, .Denied:
disabledLocationSeriveAlert()
default:
println("Failed")
}
func printCurrentCoordinates() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
println("\(locationManager.location.coordinate.latitude)")
println("\(locationManager.location.coordinate.longitude)")
}
func disabledLocationSeriveAlert() {
let alert = UIAlertController(title: "Unable to retrieve location", message: "Enable location services in system settings", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
看起来您没有CLLocationManager足够的时间来更新位置.
我查看了文档,并在声明中locationManager.location.coordinate.latitude,location是唯一一个可选的文档.它是隐式展开的,所以这就是你不需要它的原因!.
在该printCurrentCoordinates方法中,您尝试在调用后立即打印坐标startUpdatingLocation.文档location说:
nil如果从未检索过任何位置数据,则此属性的值为.
文档startUpdatingLocation说:
此方法立即返回.调用此方法会导致位置管理器获取初始位置修复(可能需要几秒钟)并通过调用其
locationManager:didUpdateLocations:方法通知您的委托.
因此,在尝试打印位置之前,您没有给位置管理员足够的时间来修复位置.
您有几个选择 - 您可以startUpdatingLocation提前调用然后打印坐标printCurrentCoordinates,或者您可以printCurrentCoordinates开始更新位置然后打印坐标locationManager:didUpdateLocations:.
| 归档时间: |
|
| 查看次数: |
634 次 |
| 最近记录: |