Ios 如何从不同的视图调用CoreLocation

Ios 如何从不同的视图调用CoreLocation,ios,swift,oop,architecture,core-location,Ios,Swift,Oop,Architecture,Core Location,我有两个视图(一个表,一个集合)。在每个视图的单元格中,都有一个按钮,点击该按钮时应获取用户的当前位置,并将其传递到变量中,以便在Deeplink中使用 我可以通过在两个视图中实现CoreLocation来实现这一点,但我试图坚持DRY,因此编写一个类或在AppDelegate中实现它一次,并在用户从任一视图的单元格中按下按钮时调用它 我看到过类似的问题,建议使用Singleton模式,或者使用NSNotificationCenter并观察按钮按下的时间 在这种情况下,有什么最佳实施方案吗?基本

我有两个视图(一个表,一个集合)。在每个视图的单元格中,都有一个按钮,点击该按钮时应获取用户的当前位置,并将其传递到变量中,以便在Deeplink中使用

我可以通过在两个视图中实现
CoreLocation
来实现这一点,但我试图坚持DRY,因此编写一个类或在AppDelegate中实现它一次,并在用户从任一视图的单元格中按下按钮时调用它

我看到过类似的问题,建议使用Singleton模式,或者使用
NSNotificationCenter
并观察按钮按下的时间


在这种情况下,有什么最佳实施方案吗?

基本上,您需要这样的方案:

final class UserLocationFinder: NSObject, CLLocationManagerDelegate {

    static let instance = UserLocationFinder()
    var currentLocation: CLLocation?
    // implement the code necessary to get the user's location and
    //   assign it to currentLocation 
}
然后在需要知道当前位置的代码中,您可以:

if let currentLocation = UserLocationFinder.instance.currentLocation {
    // the current location is known

通过这种方式,您可以满足DRY,因为代码仅在这一类中,并且您满足单一责任原则(SRP)因为你没有用额外的责任重载AppDelegate。

最简单的方法就是在你的AppDelegate中实现位置管理器,并让它公开当前位置的属性。只需从
didUpdateLocations
delegate方法更新此属性。一种稍微“干净”的方法是创建另一个对象来服务于此角色,在应用程序委托中分配它,并将其传递给视图控制器(如果必须的话,可以使用singleton)@Paulw11 thx作为答案。。我在AppDelegate中实现了CLLocationManager,并创建了一个函数来获取用户的当前位置,然后填充currentLocation的属性。但是,如果在另一个视图中实例化AppDelegate,则无法访问我编写的函数。我想我做得不对。有什么想法吗?appDelegate是个单身汉。不要实例化它。使用
UIApplication.sharedaplicatiin.delegate获取引用