我正在尝试制作一个超级简单的程序,该程序现在将从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是零,但我不知道如何解决这个问题。
答案 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()
}
}
}
在真实设备
上运行它您的错误:
ViewDidLoad
中获得速度只会被调用一次。因此,在您的代码中,每次尝试获取位置时都会开始更新。