简体   繁体   English

Swift:CMAuthorizationStatus 变化的监听器

[英]Swift: Listener for CMAuthorizationStatus changes

Is there a way to detect changes of the CMAuthorizationStatus ?有没有办法检测CMAuthorizationStatus的变化?

Currently it seems only possible to call eg CMMotionActivityManager.authorizationStatus() to get the status.目前似乎只能调用CMMotionActivityManager.authorizationStatus()来获取状态。 However, I'm looking for a way to get a change event through a listener, if the state changes (or the user disabled/enabled the Motion & Fitness permission in the settings).但是,如果状态发生变化(或用户在设置中禁用/启用运动和健身权限),我正在寻找一种通过侦听器获取更改事件的方法。

Since the status can also only be acquired through a function, I'm not able to set a KVO on the value.由于状态也只能通过函数获取,因此我无法在该值上设置 KVO。

Looking forward to your help.期待您的帮助。

I have been struggling with the same issue, I want to request the authorization once in the setup process so the user does not have to deal with the dialog later and then check for the permission every time the app gets launched.我一直在为同样的问题而苦苦挣扎,我想在设置过程中请求一次授权,这样用户就不必稍后处理对话框,然后在每次启动应用程序时检查权限。

For that I wrote the following code, first checking if the authorization was already set and otherwise initiating a call that should invoke the permission dialog.为此,我编写了以下代码,首先检查授权是否已设置,否则启动应调用权限对话框的调用。 In this call I request the activity data from now to now, which theoretically doesn't make any sense, but returns one value or an error after the permission dialog was dismissed.在这个调用中,我请求从现在到现在的活动数据,这在理论上没有任何意义,但在权限对话框被关闭后返回一个值或错误。

func checkMotionPermission(closure: @escaping (Bool) -> Void) {
    switch CMMotionActivityManager.authorizationStatus() {
    case .authorized:
        closure(true)
    case .notDetermined:
        let activityManager = CMMotionActivityManager()
        activityManager.queryActivityStarting(from: Date(), to: Date(), to: .main) { (activity, error) in
            let auth = CMPedometer.authorizationStatus()
            switch auth {
            case .authorized:
                closure(true)
            default:
                closure(false)
            }
        }
    default:
        closure(false)
    }
}

To get changes to the permission status you can call this method every time the application gets into foreground (in the AppDelegate), because that (while not being in your app) is the only time the user would be able to change the permission.要更改权限状态,您可以在每次应用程序进入前台(在 AppDelegate 中)时调用此方法,因为那(虽然不在您的应用程序中)是用户唯一能够更改权限的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM