Search code examples
iphoneobjective-ciosxcodeaccelerometer

I have basic functionality Accelerometer code, now I need to make it display text or play audio, etc


I was creating a project for a learning exercise, using the accelerometer.

I have the basic functionality of the code, now I just need to make it do something. Display a message, play audio, or display an image.

!! EDIT !!

//  ACViewController.m
//  Accelerometer
//


#import "ACViewController.h"

@interface ACViewController ()

- (void) startAccelerometer;
- (void) stopAccelerometer;

@end

@implementation ACViewController

- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration

{     //!!EDIT!!
    double const kThreshold = 2.0;
if ( fabsf(acceleration.x) > kThreshold
    || fabsf(acceleration.y) > kThreshold
    || fabsf(acceleration.z) > kThreshold)

    UILabel * theLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 640)];
    theLabel.text = @"Hello earth";
    [self.theLabel addSubView:theLabel];

//END OF EDIT }

- (void)startAccelerometer {
    UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
    accelerometer.delegate = self;
    accelerometer.updateInterval = 0.25;
}

- (void)stopAccelerometer {
    UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
    accelerometer.delegate = nil;
}

- (void)viewDidAppear:(BOOL)animated {
    [self startAccelerometer];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self stopAccelerometer];
}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Header File:

//
//  ACViewController.h
//  Accelerometer


#import <UIKit/UIKit.h>

@interface ACViewController : UIViewController <UIAccelerometerDelegate>

@end

Solution

  • Example for adding an image (and assuming you use ARC):

    In the line with the NSLog, type:

    [self.view addSubView:[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"myImage.png"]]];
    

    Example for a label (ARC):

    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 640)];
    label.text = @"Hello earth";
    [self.view addSubView:label];
    

    When not using ARC, release the instances after adding them to the view.