将 CLLocationManagerDelegate 添加到单独的 class

Add CLLocationManagerDelegate to a separate class

我想从我的 ViewController 中删除 CLLocationManagerDelegate 并添加到单独的 class 并使其可重复使用。我是 swift 的新手,所以我请求您的帮助,也许您能为我指明正确的方向。

我的目标是每次需要用户位置时调用我的 LocationHandler class 并且大多数时候我想以不同的方式处理位置(例如,按原样保存或其他时间检查位置,如果它符合某些规则则保存它等...)

如果可以处理位置更改,我想将一个函数传递给我的 LocationHandler class。

something like this: (this is just a pseudo code, I don't know how to do it properly in swift)

let locationHandler = LocationHandler()

locationHandler.handleLocationChange = (locations: [CLLocation]) - > {...}

locationHandler.getCurrentLocation()

我的第一个问题是当我从 LocationHandler 创建一个实例时,getCurrentLocation 函数是 运行 正确但 didUpdateLocations 永远不会上升(我认为委托有问题)

其次,我不知道如何将函数作为参数传递给 class

这是我的 LocationHandler class

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)")
      }
    
    
    
}

我在 viewcontroller 中这样使用它:

  let locationHandler = LocationHandler()
  locationHandler.getCurrentLocation()

正如所写,您必须确保 LocationHandler 实例是视图控制器的 属性,而不是局部变量。您要确保它不会超出范围并在委托方法有机会被调用之前被释放。