ios - 多次出现权限弹出窗口

标签 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
    }
}

最佳答案

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

相关文章:

ios - 下载图像后重新加载 CollectionView 的单元格

ios - setValue:forKey总是 swift 崩溃

swift - 快速将字符串转换为没有值的枚举

ios - 单选按钮不会通过选择而改变

ios - 在方向被另一个(iOS)强制横向后,如何恢复 UIViewController 的正确方向?

ios - 我是否需要为不同类型的注释创建实现 MKAnnotation 协议(protocol)的类?

ios - 删除单元格后使用自定义布局调整 UICollectionView 的大小

iphone - IOS 在 3 秒后淡出屏幕过渡

javascript - Safari 给出 ** 运算符(operator)错误

ios - 优化 int 递增