How to get the accelerometer to work in an iOS app using CoreMotion (Xcode 8.2.1 / iOS 10).

How to get the accelerometer to work in an iOS app using CoreMotion (Xcode 8.2.1 / iOS 10).

Question:
How do I get the accelerometer to work in an iOS app using CoreMotion (XCODE 8.2.1 / iOS 10). That is to say – I want to detect when the user shakes the device.

Answer (Shown in Objective-C):
First, you will need to import the CoreMotion Framework. You can do this by going to your Project’s Target and clicking on the ‘Build Phases’ tab.
Then expand the ‘Link Binary With Libraries’ section and press the ‘+’. Look for CoreMotion Framework. Select and add it.

Second, go to the .h file of the ViewController that you will be using this in and add this import statement at the top:
#import <CoreMotion/CoreMotion.h>

Now, your program will understand that the framework is there and ready to be leveraged!

Lastly, in your .m file of your ViewController you add this ‘motionBegan’ method. Now, you add your code inside (see my comment block) telling your device what to do when the phone/device is SHAKEN! You will see that I change the background picture when it is shaken based upon a random number generated. That’s it!

– (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {

if(event.type == UIEventSubtypeMotionShake) {

NSLog(@”The unit was shaken”);

//THIS IS WHERE YOUR CODE WILL EXECUTE WHEN THE DEVICE IS SHAKEN
// SO ADD YOUR CODE HERE (below is my code to what I did)

int value = arc4random() % 9; //This yields a number from 0 to x-1 so from 0 to 9
NSLog(@”the value was a @%i”,value);

//If random number (called value) is a zero then change my image (called intro) to background1.png (and so on)

if (value == 0) {
[intro setImage:[UIImage imageNamed:@”background1.png”]];
} else if (value == 1) {
[intro setImage:[UIImage imageNamed:@”background2.png”]];
} else if (value == 2) {
[intro setImage:[UIImage imageNamed:@”background3.png”]];
} else if (value == 3) {
[intro setImage:[UIImage imageNamed:@”background4.png”]];
} else if (value == 4) {
[intro setImage:[UIImage imageNamed:@”background5.png”]];
} else if (value == 5) {
[intro setImage:[UIImage imageNamed:@”background6.png”]];
} else if (value == 6) {
[intro setImage:[UIImage imageNamed:@”background7.png”]];
} else if (value == 7) {
[intro setImage:[UIImage imageNamed:@”background8.png”]];
} else if (value == 8) {
[intro setImage:[UIImage imageNamed:@”background9.png”]];
}

}

}

-Angelo Koutsogiannis

Leave a Reply

Your email address will not be published. Required fields are marked *