在多个类中调用了闭包?

时间:2017-12-26 10:26:28

标签: ios swift closures cllocation

我创建了一个位置管理器类,用于获取用户设备的位置。在这里,我使用了两个闭包成功和失败。我在多个类中使用此闭包。但问题是如果我在一个类中使用闭包,那么其他类中的闭包也会被调用。

class LocationManager: NSObject, CLLocationManagerDelegate {

        static let shared = LocationManager()

        let locationManager = CLLocationManager()

        /// This is the clouser that will return the current Address through google login in
        var success: (_ addrees: CLLocation) -> Void = { _ in }

        /// This clouser will return the error
        var failure: Failure = { _ in }

        //MARK: - Permission Checks
        internal var isEnabled: Bool {
            switch CLLocationManager.authorizationStatus() {
            case .authorizedAlways, .authorizedWhenInUse: return true
            default: return false
            }
        }

        private var notDetermined: Bool {
            switch CLLocationManager.authorizationStatus() {
            case .notDetermined: return true
            default: return false
            }
        }

        func start() -> Void {
            locationManager.delegate = self
            locationManager.desiredAccuracy =  kCLLocationAccuracyBest
            if isEnabled {
                locationManager.startUpdatingLocation()
            } else if notDetermined {
                request()
            } else {
                failure(DIError.locationPermissionDenied)
            }
        }
        func request() -> Void {
            locationManager.requestWhenInUseAuthorization()
        }

        //MARK:Location Manager Delegate
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            if let currentLocation: CLLocation = manager.location {
                self.success(currentLocation)
            }else {
                self.failure(DIError.locationPermissionDenied)
            }
            locationManager.stopUpdatingLocation()
            locationManager.delegate = nil

        }

        func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
            failure(DIError.unKnowError())
        }

        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
            switch status {
            case .notDetermined:
                // If status has not yet been determied, ask for authorization
                request()
                break
            case .authorizedWhenInUse:
                // If authorized when in use
                manager.desiredAccuracy = kCLLocationAccuracyBest
                manager.startUpdatingLocation()
                break
            case .authorizedAlways:
                // If always authorized
                manager.desiredAccuracy = kCLLocationAccuracyBest
                manager.startUpdatingLocation()
                break
            case .restricted: failure(DIError.locationPermissionDenied)
            // If restricted by e.g. parental controls. User can't enable Location Services
                break
            case .denied:
                failure(DIError.locationPermissionDenied)
                // If user denied your app access to Location Services, but can grant access from Settings.app
                break
            }
        }
}

课堂上用于检查位置是否可用的关闭

 LocationManager.shared.start()
                LocationManager.shared.success = { location in
                        _ = LocationManager.shared.getAddressFromLocation(location: location, completion: { (address) in
                            Utility.shared.saveLocation(objCLLocatin: location.coordinate,address: address)

                        })
                }

                LocationManager.shared.failure = {
                    DILog.print(items: "Failed location")
                    if $0.code == .locationPermissionDenied {
                        self.showPlacePicker()
                        return
                    } else {
                        Utility.shared.showNAlert(titleStr: $0.title, messageStr: $0.message, actionStr: ["Ok".localized], tag: "")
                        DILog.print(items: "other denied")
                    }
                }

如果我在另一个类中检查位置,也会为其他类调用失败关闭。所以一个闭包调用了多个类。

修改 我有两个班级A& B级。我在第一个控制器上获取位置&相应地检查成功和失败块被调用。 我从第一个控制器推到第二个控制器,然后我再次检查当前位置。所以如果在第二个控制器上,即。 B.因此,如果第二个控制器调用了故障块,那么第一个控制器也会调用它。 我很惊讶为什么会这样?

1 个答案:

答案 0 :(得分:0)

如果你对单个类使用单例类,这是正常的行为,每次你设置success = ...时闭包都会被覆盖,只有最后一个被调用,并且它的最后一个被设置了,不是当前使用闭包的类

删除singleton(为每个类创建不同的实例)或使用类似于基于字典的处理程序(例如[" ClassName&#34 ;: successClosure]),这与委托相同,如果使用委托,那么也有每次更改处理类时都要覆盖