【发布时间】:2020-02-16 19:17:47
【问题描述】:
我想从我的 ViewController 中删除 CLLocationManagerDelegate 并添加到一个单独的类中并使其可重用。我对 swift 很陌生,所以我请求您的帮助,也许您可以为我指明正确的方向。
我的目标是每次我想要用户的位置时调用我的 LocationHandler 类,并且大多数时候我想以不同的方式处理位置(例如,只需按原样保存或其他时间检查位置以及是否满足某些规则然后保存它等...)
如果可以处理位置更改,我想将一个函数传递给我的 LocationHandler 类。
类似这样的:(这只是一个伪代码,我不知道如何在swift中正确执行)
让 locationHandler = LocationHandler()
locationHandler.handleLocationChange = (locations: [CLLocation]) - > {...}
locationHandler.getCurrentLocation()
我的第一个问题是,当我从 LocationHandler 创建一个实例时,getCurrentLocation 函数运行正常,但 didUpdateLocations 从未上升(我认为委托有问题)
其次我不知道如何将函数作为参数传递给类
这是我的 LocationHandler 类
import Foundation
import CoreLocation
class LocationHandler: NSObject, CLLocationManagerDelegate{
let locationManager = CLLocationManager()
override init(){
super.init()
locationManager.delegate = self
}
func getCurrentLocation(){
if CLLocationManager.locationServicesEnabled() {
switch CLLocationManager.authorizationStatus() {
case .notDetermined, .restricted, .denied:
print("No access")
case .authorizedAlways, .authorizedWhenInUse:
print("Access")
@unknown default:
break
}
} else {
print("Location services are not enabled")
}
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
print("Found user's location: \(location)")
//do something with the location
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Failed to find user's location: \(error.localizedDescription)")
}
}
我像这样在视图控制器中使用它:
let locationHandler = LocationHandler()
locationHandler.getCurrentLocation()
【问题讨论】:
-
您的
LocationHandler实例是您的视图控制器的属性吗?您显然希望确保它不会超出范围并被释放。我也没有看到你从哪里开始定位服务。您可能不想只请求位置,而是打开位置服务,以便它有机会预热并获得越来越准确的位置。 -
@Rob,是的,问题是我在函数级别创建了实例,当我移动到 vc 级别时它开始正常工作。
标签: ios swift locationmanager