我在 swift 2 中有一个项目。当我第一次启动应用程序时,启动屏幕上会出现三种不同类型的权限弹出窗口(推送通知、位置、照片)。我添加了位置和照片的权限在info.plist中
问题是,当应用程序启动时,一个(位置)弹出窗口出现并消失,没有任何点击,然后其他(照片)弹出窗口出现并在几秒钟后消失,没有任何点击。几秒钟后,弹出窗口一个接一个地出现,现在弹出窗口会显示在屏幕上,直到我单击任何一个选项。
我只想在用户点击按钮时显示一次权限弹出窗口。我已经搜索过它,但我找到的所有解决方案都是最新版本的 swift。任何与此相关的建议都值得赞赏。
import CoreLocation
private var locationManager: CLLocationManager!
private var locationHandler: ((location: CLLocation?,error: NSError?) -> Void)?
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
func requestCurrentLocation(completionHandler:((location: CLLocation?,error: NSError?)->Void)!) {
locationHandler = completionHandler
if #available(iOS 9.0, *) {
locationManager.requestLocation()
} else {
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let locationHandler = locationHandler, let location = locations.first {
locationHandler(location: location, error: nil)
self.locationHandler = nil
locationManager.stopUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
if let locationHandler = locationHandler {
locationHandler(location: nil, error: error)
self.locationHandler = nil
}
}
最佳答案
关键是 CLLocationManager 始终处于事件状态
import CoreLocation
class LocationManager: NSObject {
static let shared = LocationManager()
private lazy var locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
return manager
}()
private override init() {
super.init()
}
func askForPermission() {
locationManager.requestWhenInUseAuthorization()
}
func requestLocation() {
locationManager.requestLocation()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
// do something
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// do something
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// do something
}
}
关于ios - 多次出现权限弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47884887/