Getting accelerometer data in background using CoreMotion

馋奶兔 提交于 2019-12-03 00:38:15

Put this code right in front of that line (after making a member variable called bgTaskID of type UIBackgroundTaskIdentifier):

UIApplication *application = [UIApplication sharedApplication];
        __weak __typeof(&*self)weakSelf = self;
        self.bgTaskID = [application beginBackgroundTaskWithExpirationHandler:^{
            __strong __typeof(&*weakSelf)strongSelf = weakSelf;

            NSLog(@"BG TASK EXPIRED!");

            if (strongSelf) {
                [application endBackgroundTask:strongSelf.bgTaskID];
                strongSelf.bgTaskID = UIBackgroundTaskInvalid;
            }
        }];

It can be done by using CoreMotion framework. You have to import CoreMotion framework, then #import <CoreMotion/CoreMotion.h> in your appdelegate.

Here motionManager is object of CMMotionManager.

xData, yData, zData are double values to store accelerometer data.

if (motionManager ==nil) {
    motionManager= [[CMMotionManager alloc]init];
}
[motionManager startAccelerometerUpdates];

[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
    xData = accelerometerData.acceleration.x;
    yData = accelerometerData.acceleration.y;
    zData = accelerometerData.acceleration.z;
}];

You have to do it in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions.

You can then use these value of xData, yData, zData where ever you want by appdelegate object, even in background.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!