0

I've tried several method but I cannot find a working method to replace my

[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / kAccelerometerFrequency)];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];

most recently i've tried to replace that with

motionManager = [[CMMotionManager alloc] init];
motionManager.accelerometerUpdateInterval = (1.0 / kAccelerometerFrequency);

But it does not seem to work with my void

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    CGPoint pt = theCar.center;
    CGFloat accel = acceleration.x * kAccelerationSpeed;

float halfCarWidth = theCar.frame.size.width / 2;
    if(pt.x - halfCarWidth + accel > 0 && pt.x + halfCarWidth + accel < 320) {
        pt.x += accel;
    }

    [theCar setCenter:pt];
}

So what do I replace the sharedAccelerometer with since it was depreciated in iOS 5

inVINCEable
  • 2,167
  • 3
  • 25
  • 49

1 Answers1

1

There is no delegate message with motion manager. Use a timer (NSTimer) and poll the motion manager for its values, at intervals.

self.motman = [CMMotionManager new];
if (!self.motman.accelerometerAvailable) {
    // report error or whatever
    return;
}
self.motman.accelerometerUpdateInterval = 1.0 / 30.0;
[self.motman startAccelerometerUpdates];
self.timer =
    [NSTimer
        scheduledTimerWithTimeInterval:self.motman.accelerometerUpdateInterval
        target:self selector:@selector(pollAccel:) userInfo:nil repeats:YES];

Now pollAccel: is called repeatedly. Pull out the accelerometer info:

CMAccelerometerData* dat = self.motman.accelerometerData;
CMAcceleration acc = dat.acceleration;
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • And see my discussion here: http://www.apeth.com/iOSBook/ch35.html#_raw_acceleration – matt Apr 23 '14 at 18:18
  • 1
    A better alternative to explicit polling is to use the block call-back functions such as `startAccelerometerUpdatesToQueue:withHandler:` – David Berry Apr 23 '14 at 18:29
  • Agree with @David - while the answer is technically correct and gives you a conceptual understanding of what's going on, explicit polling shouldn't be put into production apps IMHO. Not to say the answer doesn't fulfill its responsibility, just my 2 cents. – Jai Govindani Apr 23 '14 at 20:38
  • @David No, Apple explicitly tells you it's fine to poll CMMotionManager. "An app can take one of two approaches when receiving motion data, by handling it at specified update intervals or periodically sampling the motion data." Periodically sampling = polling. They call this "the pull approach": https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/motion_event_basics/motion_event_basics.html#//apple_ref/doc/uid/TP40009541-CH6-SW4 – matt Apr 23 '14 at 21:00