我阅读了Radar.io
(https://radar.io/documentation/sdk#ios)iOS SDK文档,我很好奇我是如何创建自定义的
locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
功能。
class ViewController: UIViewController, RadarDelegate {
override func viewDidLoad() {
super.viewDidLoad()
Radar.setDelegate(self)
}
}
和
Radar.trackOnce(completionHandler: { (status: RadarStatus, location: CLLocation?, events: [RadarEvent]?, user: RadarUser?) in
// do something with status, location, events, user
})
来源:https://radar.io/documentation/sdk#ios
我如何在这样的自定义类中获取位置更新和控制CLLocationManager?
protocol MyRadarCloneDelegate {
}
class MyRadarClone {
static func setDelegate(_ delegate:) {
}
static func startTracking() {
}
// some other function for control CLLocationManager
}
如果我正确理解你的问题,你想从location
访问你的Radar.trackOnce
到你的自定义类。
你可以这样做。
以这种方式更新您的startTracking
方法:
func startTracking(location: CLLocation) {
//do somtrhing with your location
print(location)
}
并在您的Radar.trackOnce
方法添加以下代码:
guard let userLocation = location else {return}
let myRadar = MyRadarClone()
myRadar.startTracking(location: userLocation)
希望这会有所帮助。
注意:代码未经过测试。
不要为此创建任何自定义协议或功能
我认为这是一个好主意
我假设目标是创建一个自定义生命周期方法,其作用类似于viewDidLayoutSubviews
,而不是locationManagerDidGetLocation
,或者其他东西,在您放入的任何视图控制器中只调用一次。如果相反,您只想扩展位置管理器的委托对于其他视图控制器,策略是相同的(最后进行小调整):
class SomeViewController: UIViewController {
func locationManagerDidGetLocation() {
doSomethingThatRequiresUserLocation()
}
}
CLLocationManagerDelegate
有一种新的位置数据方法(以及一种新的位置数据)。只需发布通知:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
NotificationCenter.default.post(name: .locationManagerDidUpdateLocations, object: nil)
}
您还可以在静态结构变量或应用程序委托中共享应用程序中的位置值:
struct CurrentLocation {
static var coordinate: CLLocationCoordinate2D?
}
并通过代表更新它:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// update shared property
let lastLocation = locations.last!
CurrentLocation.coordinate = lastLocation.coordinate
// post app-wide notification
NotificationCenter.default.post(name: .locationManagerDidUpdateLocations, object: nil)
}
要访问该值,只需在应用中的任何位置调用CurrentLocation.coordinate
即可。
然后只需向一个对象添加一个通知观察器,就像UIViewController
一样,监听该帖子:
class SomeViewController: UIViewController {
func addNotificationObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(locationManagerDidUpdateLocationsHandler), name: .locationManagerDidUpdateLocations, object: nil)
}
}
当第一个帖子到达时,删除观察者,因此只调用一次,并调用自定义方法:
@objc func locationManagerDidUpdateLocationsHandler() {
NotificationCenter.default.removeObserver(self, name: .locationManagerDidUpdateLocations, object: nil)
locationManagerDidGetLocation()
}
现在,它就像常规生命周期方法一样,当用户的位置可用时只触发一次:
class SomeViewController: UIViewController {
func locationManagerDidGetLocation() {
doSomethingThatRequiresUserLocation()
}
}
当然,您可以不删除观察者,并使其功能类似于位置管理器的扩展代理。如果这些视图控制器没有持续应用程序的生命周期,请不要忘记删除deinit
中的所有观察者。