如何解决完成处理程序中的代码自我重复多次
我为托管的 CLLocationManager 创建了一个单例并获取用户的位置。这是课程:
import Foundation
导入核心位置
typealias locationCompletionHandler = (_ isLocationAllowed: Bool,_ userCoordinate: CLLocationCoordinate2D?) -> Void
class LocationManager: NSObject {
static let shared = LocationManager()
var locationManagerCallBack: locationCompletionHandler!
var locationManager: CLLocationManager!
override init() {}
func setUpUserLocation(completion: @escaping locationCompletionHandler) {
locationManagerCallBack = completion
locationManager = CLLocationManager()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
} else {
locationManagerCallBack(false,nil)
}
}
}
扩展位置管理器:CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager,didChangeAuthorization status: CLAuthorizationStatus) { 切换状态{ 案例 .denied,.restricted: locationManagerCallBack(false,nil) 案例 .authorizedAlways,.authorizedWhenInUse: locationManager.startUpdatingLocation() 案例.notDetermined: locationManager.requestAlwaysAuthorization() @unkNown 默认值: 休息 } }
func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first?.coordinate else { return }
locationManagerCallBack(true,location)
locationManager.stopUpdatingLocation()
}
}
这是我实现单例时的代码:
@IBAction func transferButtonPress(_ sender: UIButton) {
LocationManager.shared.setUpUserLocation { (isLocationEnabled,coordinate) in
if isLocationEnabled {
if coordinate != nil {
print("---------- COORDINATE \(coordinate)")
self.presenter.presentTransfers(accountModel: self.accountModel)
} else {
let cancelAction = UIAlertAction(title: String.Localized.cancel,style: .cancel,handler: nil)
let openAppPreferencesAction = UIAlertAction(title: String.Localized.accept,style: .default) { _ in
LinkUtils.link(url: UIApplication.openSettingsURLString)
}
AlertController.showAlert(title: String.Localized.geolocationDeniedTitle,message: String.Localized.geolocationDeniedBody,actions: [openAppPreferencesAction,cancelAction])
}
} else {
let cancelAction = UIAlertAction(title: String.Localized.cancel,handler: nil)
let openAppPreferencesAction = UIAlertAction(title: String.Localized.accept,style: .default) { _ in
LinkUtils.link(url: UIApplication.openSettingsURLString)
}
AlertController.showAlert(title: String.Localized.geolocationUnableTitle,message: String.Localized.geolocationUnableBody,cancelAction])
}
}
}
问题是闭包中的代码执行了几次,所以下一个屏幕加载了几次蚂蚁看起来像一个错误。我认为问题可能出在 didUpdateLocations 方法中,但我不太确定
为什么会这样?我怎样才能只执行一次该代码?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。