iosobjective-ccore-motionuiaccelerometer

Replace sharedAccelerometer with motionManager iOS


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


Solution

  • 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;