Swift:尝试打印CLLocationSpeed时出现异常“在展开Optional值时意外发现nil”

时间:2015-05-07 00:52:03

标签: ios swift

我正在尝试制作一个超级简单的程序,该程序现在将从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.
}


}

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

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

1 个答案:

答案 0 :(得分:1)

首先将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更改时开始更新