我有以下代码来获取位置更新(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)
}
}
我只在[{1}}中获得一次更新:在致电didUpdateLocations
后,startTracking
只会被调用一次,并且在5秒内GPS指示消失。
一些细节:
didUpdateLocations
中放置断点,它将会被打4到5次。我在这里看到了类似问题的答案(例如Implement CLLocationManagerDelegate methods in Swift),但它对我来说仍然无效。
我做错了什么?
谢谢!
答案 0 :(得分:4)
Xcode 6为位置服务做了很多补充。
1)您需要更改info.plist文件以包含String" NSLocationWhenInUseUsageDescription"键。这个价值将是您启用位置服务的应用程序的推理:"使用位置服务来跟踪您的运行"。
2)使用" [self.locationManager requestWhenInUseAuthorization];"在您的代码中,弹出窗口会显示上面的字符串。
有关WWDC 2014视频的更多信息。
答案 1 :(得分:1)
这就解决了这个问题 - 我为didUpdateLocations
添加了很短的睡眠时间:
func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
println("locations = \(locations)")
NSThread.sleepForTimeInterval(0.001)
}
我同意@Mike认为它看起来像一个非常奇怪的修复,但它是一个修复。如果有人会找到更好的解释/答案,请发布。
答案 2 :(得分:0)
尝试使用此方法查看您的位置管理器是否正在暂停:
func locationManagerDidPauseLocationUpdates(manager: CLLocationManager!)
如果您要暂停,请尝试将准确度更改为kCLLocationAccuracyBest
。
答案 3 :(得分:0)
您可以在Swift 4
中使用它,
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.delegate = self
self.locationManager.startUpdatingLocation()