【发布时间】:2015-04-24 11:30:10
【问题描述】:
我在使用 CLLocationManager 时遇到了一些问题。此代码曾经在 iOS 8.2 上工作,但自从升级到 8.3 后它就不起作用了。这是设置在启动时调用的位置管理器的代码。
let distanceThreshold:CLLocationDistance = 100.0
var currentLocation:CLLocationCoordinate2D?
override init() {
assert(locMan == nil)
super.init()
locMan = self
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
currentLocation = manager.location.coordinate
if UIApplication.sharedApplication().applicationState == .Background {
PlacesManager.fetchNearbyPlaces(LocationManager.getLocationManager().currentLocation!, radius: distanceThreshold, callback: placesCallback)
}
}
使用此代码,didUpdateLocations 永远不会被调用,尽管它之前被调用过。 我已将相关条目添加到 Info.plist 文件中:
我在设备和模拟器上都试过了,都不管用。事实上,如果我删除应用并重新安装,它似乎不再请求位置授权。
我知道我错过了一些愚蠢的东西,但我无法锻炼它到底是什么。
如果有人能提供任何帮助,我将不胜感激。
干杯, 杰拉德
【问题讨论】:
-
不应该
locationManager是实例变量而不是init中的局部变量? -
是的,我注意到很多人这样做,但从未真正使用实例变量。每个位置管理器回调都提供管理器,因此实际上不需要保留对它的引用,除非您想停止它或在回调之外使用它。
-
CLLocationManager documentation 说:“要配置和使用 CLLocationManager 对象来传递事件...创建 CLLocationManager 类的实例并将对它的强引用存储在应用程序的某处。保持强在涉及该对象的所有任务完成之前,需要对位置管理器对象的引用。因为大多数位置管理器任务是异步运行的,所以将位置管理器存储在局部变量中是不够的。"
-
太棒了。谢谢,我真的不明白为什么需要这样做,但那是固定的。我猜必须是垃圾收集吗?让它成为一个答案,我会给你信用。谢谢安娜。
标签: ios swift core-location