我有以下代码来获取位置更新(iOS 7):
import UIKit
import CoreLocation
class FirstViewController: UIViewController, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func startTracking(sender : AnyObject) {
NSLog("Start tracking")
if (locationManager == nil) {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.pausesLocationUpdatesAutomatically = false
}
locationManager.startUpdatingLocation()
}
@IBAction func stopTracking(sender : AnyObject) {
NSLog("Stop tracking")
stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
NSLog("Error" + error.description)
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
println("locations = \(locations)")
}
func locationManager(manager: CLLocationManager!,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Access: Restricted"
break
case CLAuthorizationStatus.Denied:
locationStatus = "Access: Denied"
break
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Access: NotDetermined"
shouldIAllow = true
break
default:
locationStatus = "Access: Allowed"
shouldIAllow = true
}
NSLog(locationStatus)
}
}我在didUpdateLocations中只得到一个更新:调用startTracking之后,didUpdateLocations只会被调用一次,而在5秒内,GPS指示器就消失了。
一些细节:
didUpdateLocations中放置断点,它将被击中4-5次。我在这里看到了类似问题的答案(比如Implement CLLocationManagerDelegate methods in Swift),但对我来说仍然行不通。
我做错了什么?
谢谢!
发布于 2014-08-22 17:22:53
Xcode 6为Location Services添加了很多内容。
1)您需要更改info.plist文件以包含字符串"NSLocationWhenInUseUsageDescription“键。它的价值将是您的应用程序对打开位置服务的推理:“使用位置服务来跟踪您的运行”。
2)在代码中使用"self.locationManager requestWhenInUseAuthorization;“,使弹出与上面的字符串一起出现。
更多信息是在WWDC 2014视频。
发布于 2014-06-26 14:47:27
这就是解决问题的原因--我给didUpdateLocations增加了一个很短的睡眠时间
func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
println("locations = \(locations)")
NSThread.sleepForTimeInterval(0.001)
}我同意“Mike”的观点,它看起来像一个非常奇怪的修复,但它是一个修复。如果有人能找到更好的解释/答案,请把它贴出来。
发布于 2014-06-23 17:19:03
尝试实现此方法以查看您的位置管理器是否被暂停:
func locationManagerDidPauseLocationUpdates(manager: CLLocationManager!)如果您要暂停,请尝试将准确性更改为kCLLocationAccuracyBest。
https://stackoverflow.com/questions/24368866
复制相似问题