简体   繁体   中英

Accessing the accelerometer in iOS while running in the background

I'm new to iOS programming. I'm wanting to write an app that has constant access to the accelerometer, and barometric pressure sensor of the iPhone 6, while running in the background.

In my research, I've found that people have done it using the Location Updates background mode, but this only worked for 10 minutes before the app was suspended (and this changed to 3 minutes in iOS 6?). I'd also read about using the audio background mode playing a mute sound as a way to work around that time limit. This seems like a substandard solution though.

I'm wondering then how an app something like Sleep Cycle does this, as it seems like it must have constant access to the accelerometer.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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