【发布时间】:2017-11-19 07:00:16
【问题描述】:
我正在获取用户位置,我创建了单例类来在需要时获取用户位置。但它正在创建保留周期。如果我使用 LocationManager 类,则不会调用 deint 。如果我不使用这个类这个de init 按预期正确调用。
class LocationManager: NSObject, CLLocationManagerDelegate {
private var clLocationManager: CLLocationManager?
private var SuccessBlock:((_ latitude: String, _ longitude: String)->Void)?
private var OnFailedBlock:(()->Void)?
private var lat: String?
private var long: String?
static let shared: LocationManager = {
let instance = LocationManager()
return instance
}()
private override init() {
super.init()
}
private func invokeLocationManager() {
if self.clLocationManager == nil {
self.clLocationManager = CLLocationManager()
self.clLocationManager?.delegate = self
}
self.clLocationManager?.requestWhenInUseAuthorization()
self.clLocationManager?.startUpdatingLocation()
}
func getUserCurrentLocation(onSucessBlok onSucessBlock:@escaping (_ lat: String, _ long: String)->Void, onFailedBlok onFailedBlock:@escaping ()->Void) ->Void {
self.SuccessBlock = onSucessBlock
self.OnFailedBlock = onFailedBlock
self.invokeLocationManager()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.clLocationManager?.stopUpdatingLocation()
if locations.count > 0 {
let userLocation = locations[0]
self.long = String(userLocation.coordinate.longitude);
self.lat = String(userLocation.coordinate.latitude);
if self.SuccessBlock != nil {
self.SuccessBlock!(self.lat!, self.long!)
self.SuccessBlock = nil
}
} else {
if self.OnFailedBlock != nil {
self.OnFailedBlock!()
self.OnFailedBlock = nil
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if self.OnFailedBlock != nil {
self.OnFailedBlock!()
self.OnFailedBlock = nil
}
}
}
从WKInterfaceController,我调用这个方法
override func willActivate() {
super.willActivate()
self.getUserLocation()
}
private func getUserLocation() {
LocationManager.shared.getUserCurrentLocation(onSucessBlok: { [weak self] (lat, long) in
if CommonHelper.isStringValid(string: lat) && CommonHelper.isStringValid(string: long) {
self?.fillInfoToDictionary(value:lat, key: KLatitude, type: InfoType.Acceleration)
self?.fillInfoToDictionary(value:long, key: KLongitude, type: InfoType.Acceleration)
}
}, onFailedBlok: {
self.fillInfoToDictionary(value:"0", key: KLatitude, type: InfoType.Acceleration)
self.fillInfoToDictionary(value:"0", key: KLongitude, type: InfoType.Acceleration)
})
}
每次调用 WKInterface 的 willActivate 时,我都会调用这个 getUserCurrentLocation 方法。 还有其他更好的方法吗?这样就不会创建保留周期。
【问题讨论】: