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?
Asked
Active
Viewed 6,079 times
7
Madu
- 4,849
- 9
- 44
- 78
-
possible duplicate of [iOS - is Motion Activity Enabled in Settings > Privacy > Motion Activity](http://stackoverflow.com/questions/21005990/ios-is-motion-activity-enabled-in-settings-privacy-motion-activity) – Brandon Schlenker May 03 '14 at 01:47
4 Answers
12
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
Community
- 1
- 1
Brandon Schlenker
- 5,078
- 1
- 36
- 58
11
With introduction of IOS 11.* there is the possibility to call CMMotionActivityManager.authorizationStatus() which gives you a detailed status.
spassas
- 4,778
- 2
- 31
- 39
Hardy_Germany
- 1,259
- 13
- 19
4
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")
}
})
Zack Braksa
- 1,628
- 18
- 26
-
2Ok kids, remember to add manager.stopActivityUpdates() to the handler. :) – CodeReaper Mar 18 '16 at 09:42
-
-
3@CodeReaper I don't think that's necessary, is it? `manager.startActivityUpdates(to:withHandler:)` has not been called. `manager.queryActivityStarting(from:to:to:withHandler:)` is a one-shot request for motion data and doesn't continuously update. – Stuart Aug 27 '18 at 17:59
3
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()
})
}
makle
- 1,237
- 1
- 15
- 21