Swift:尝试打印CLLocationSpeed时发生exception“意外地发现零,同时展开一个可选值”

我正在尝试制作一个超级简单的程序,它将从iPhone的gps打印速度。 这是我的代码到目前为止:

// // ViewController.swift // GpsSpeed // // Created by Jacob Sandum on 4/18/15. // Copyright (c) 2015 Jacob Sandum. All rights reserved. // import UIKit import CoreLocation let locationManager = CLLocationManager() class ViewController: UIViewController, CLLocationManagerDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. locationManager.delegate = self if CLLocationManager.authorizationStatus() == .NotDetermined { locationManager.requestAlwaysAuthorization() } locationManager.desiredAccuracy=kCLLocationAccuracyBest if CLLocationManager.locationServicesEnabled() { locationManager.startUpdatingLocation() } var speed: CLLocationSpeed = CLLocationSpeed() speed = locationManager.location.speed println(speed); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

当我尝试运行这个代码时,我得到这个致命的exception: unexpectedly found nil while unwrapping an Optional value (lldb)

我认为CLLocationSpeed是零,但我不知道如何解决这个问题。

首先将NSLocationAlwaysUsageDescription添加到您的info.plist文件中

那么完整的代码是

  import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. locationManager.delegate = self if NSString(string:UIDevice.currentDevice().systemVersion).doubleValue > 8 { locationManager.requestAlwaysAuthorization() } locationManager.desiredAccuracy=kCLLocationAccuracyBest } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var speed: CLLocationSpeed = CLLocationSpeed() speed = locationManager.location.speed println(speed); } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status != CLAuthorizationStatus.Denied{ locationManager.startUpdatingLocation() } } } 

真实的设备上运行它

你的错误:

  1. 不要在ViewDidLoad获得速度,它只会被调用一次。所以,在你的代码中,每次你尝试获取位置之前,它开始更新。
  2. 在位置更新时获得速度会更好
  3. auth更改后开始更新会更好