0

I am trying to get the accelerometer values on a phone and return them in a function. The following code never gets to the "Reached" NSLog. I am calling this in my viewDidLoad and it goes into the if statement. Any help is greatly appreciated.

- (NSArray *)getAccelerometerValues{
    //Get the current x y and z
    __block float x, y, z;
    CMMotionManager *motionManager = [[CMMotionManager alloc] init];
    motionManager.accelerometerUpdateInterval = .5;
    if(motionManager.accelerometerAvailable){
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [motionManager startAccelerometerUpdatesToQueue:queue
                                                 withHandler:^(CMAccelerometerData *accelerometerData, NSError * error) {
                                                     NSLog(@"Reached");
                                                     x = (accelerometerData.acceleration.x * 180) /  M_PI;
                                                     y = (accelerometerData.acceleration.y * 180) / M_PI;
                                                     z = (accelerometerData.acceleration.z * 180) / M_PI;
                                                     NSLog(@"X: %f Y: %f Z: %f",x,y,z);
                                                 }];
    }
    NSArray *xyz = [[NSArray alloc] initWithObjects:
                    [NSNumber numberWithFloat:x],
                    [NSNumber numberWithFloat:y],
                    [NSNumber numberWithFloat:z],
                    nil];
    return xyz;
jsherbz
  • 11
  • 4
  • 1
    I'm wondering if `motionManager` has to be retained (`@property (nonatomic, strong) CMMotionManager *motionManager;`). Plus, I guess that your returns should have 0,0,0 at first (async?). – Larme May 26 '16 at 12:58
  • Yep that was the issue I had and this fixed it. Thank you. – jsherbz May 26 '16 at 13:02
  • 1
    I have flagged as duplicate from Swift Question, but the fondamental issue (`CMMotionManager` object being released too soon) is the clearly the same. – Larme May 26 '16 at 13:10

0 Answers0