【发布时间】:2017-08-19 23:06:05
【问题描述】:
所以我在几个月前编写了这段代码(当时 iOS 10.1 还是最新版本),它运行良好。但是,当我最近尝试使用 iOS 10.2 时,CLLocationManager 似乎没有调用didUpdateLocation 函数。当我将模拟器恢复到 iOS 10.1 时,它又可以工作了。
当我试图查找我的问题时,我得到的只是 iOS 8 更新的解决方案,您还必须在其中更新 info.plist。因此,我想知道对于 iOS 10.2 的 CoreLocation 是否需要做一些额外的事情。我在 info.plist 中有 Privacy - Location When In Use Usage Description 和 Privacy - Location Always Usage Description 信息属性。
let locationManager = CLLocationManager()
var userLocation:CLLocation = CLLocation()
func handleSwitchChanged() {
if onlineSwitch.isOn {
if CLLocationManager.authorizationStatus() != .authorizedAlways {
locationManager.requestWhenInUseAuthorization()
onlineSwitch.isOn = false
return
}
(mainScreen as! MainScreenController).currUser.isOnline = 1
determineUserLocation()
} else {
(mainScreen as! MainScreenController).currUser.isOnline = 0
removeFromFirebase()
}
}
func determineUserLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations[0] as CLLocation
}
【问题讨论】:
-
你在哪里设置
delegate?我的意思是...打电话给handleSwitchChanged()哪个叫determineUserLocation()?另外,!= .authorizedAlways不应该是!= .authorizedWhenInUse吗? -
@AlejandroIván 我在
determineUserLocation()中设置了代理,只要按下按钮就会调用它。我认为是.authorizedAlways。我试过.authorizedWhenInUse,但没用。 -
是的,但您正在请求使用时授权。这意味着它永远不会永远存在,因此,它总是会进入那个“如果”然后返回。尝试删除该返回,以便您的函数实际调用确定用户位置()
-
我在应用程序的其他地方请求始终授权。看看那个时间点的值,
CLLocationManager.authorizationStatus()是.authorizedAlways。 -
1.您的问题很难重现,因为我们不知道何时/何地调用
handleSwitchChanged,也不知道onlineSwitch是否为true。 2. 你也启用了背景模式中的位置吗? 3. 除此之外...您的代码看起来不错,但为了安全起见,将您的locationManager.startUpdatingLocation()包装在主线程调度中。您可能遇到运行循环问题,这样您的代码将在活动的运行循环上运行
标签: ios swift xcode core-location