I want to get the authorization status for CMMotionActivityManager. For other services like calendar and location we have some property in the API that gives us the user authorization status for these classes. How i can get the authorization status for CMMotionActivityManager class?

有帮助吗?

解决方案

CMMotionActivityManager does not currently offer a way to check authorisation status directly like other frameworks.

iOS - is Motion Activity Enabled in Settings > Privacy > Motion Activity

However, as the comments in the above question mention, if you attempt a query using

queryActivityStartingFromDate:toDate:toQueue:withHandler

and the user has not authorised your application, the handler (CMMotionActivityQueryHandler) will return this error.

CMErrorMotionActivityNotAuthorized

其他提示

With introduction of IOS 11.* there is the possibility to call CMMotionActivityManager.authorizationStatus() which gives you a detailed status.

Here's how I'm doing it :

manager = CMMotionActivityManager()

let today = NSDate()

manager.queryActivityStartingFromDate(today, toDate: today, toQueue: NSOperationQueue.mainQueue(),
    withHandler: { (activities: [CMMotionActivity]?, error: NSError?) -> Void in

        if let error = error where error.code == Int(CMErrorMotionActivityNotAuthorized.rawValue){
            print("NotAuthorized")
        }else {
            print("Authorized")
        }

})

I had to adjust Zakaria's answer a bit for Swift 3.0 and also the new Error made problems, so I had to convert it back to NSError to get the code but this is how my function looks now. Thanks!

func triggerActivityPermissionRequest() {
  let manager = CMMotionActivityManager()
  let today = Date()

  manager.queryActivityStarting(from: today, to: today, to: OperationQueue.main, withHandler: { (activities: [CMMotionActivity]?, error: Error?) -> () in
    if error != nil {
      let errorCode = (error! as NSError).code
      if errorCode == Int(CMErrorMotionActivityNotAuthorized.rawValue) {
        print("NotAuthorized")
      }
    } else {
    print("Authorized")
  }
  manager.stopActivityUpdates()
  }) 
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top