【发布时间】:2014-06-23 14:46:26
【问题描述】:
我有以下代码来获取位置更新(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),但它仍然对我不起作用。
我做错了什么?
谢谢!
【问题讨论】:
-
所以你是说结果只打印了一次,但是断点被打了多次?
-
@Mike 是的,没错。我刚刚将以下行
NSThread.sleepForTimeInterval(1.0)添加到didUpdateLocations处理程序(睡眠线程 1 秒)。现在一切正常。绝对我错过了一些非常愚蠢的东西:(。 -
这绝对看起来很时髦 - 我不会排除这可能是 Xcode 6 测试版错误的可能性......
标签: ios swift cllocationmanager