权限弹出窗口多次出现

时间:2017-12-19 10:28:05

标签: ios iphone swift permissions

我在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
    }
}

1 个答案:

答案 0 :(得分:0)

关键是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
    }
}