One of the flashiest features of iOS is the accelerometer. The accelerometer detects the device’s real-world orientation by tracking the force of the earth’s gravity on its X, Y, and Z axes. You can also use accelerometer data to detect changes in the device’s velocity.
In this chapter, you are going to use the accelerometer to skew the center of the HypnosisView according to the device’s orientation: when the user tilts the phone, the center will slide in the direction of the tilt, as shown in Figure 8.1.
To receive accelerometer data, your application needs to get hold of the application’s shared instance of UIAccelerometer and give it an updateInterval and a delegate. The delegate needs to implement the method accelerometer:didAccelerate:. This method reports changes in the accelerometer data every updateInterval seconds in the form of a UIAcceleration object.
Open the HypnoTime project. Before you add any code, you need to decide which object will be the UIAccelerometer delegate. There are two options:
If the HypnosisView is the accelerometer delegate, it becomes a self-contained object, which makes reusing it simpler. The problem is there can only be one accelerometer delegate. What if other objects need input from the accelerometer? HypnosisView can’t forward information on to other objects – it’s not a controller. Therefore, the better option is to let HypnosisViewController be the delegate and receive the accelerometer updates, as shown in Figure 8.2. HypnosisViewController can easily inform the HypnosisView of a change in orientation, and it can inform other objects, too, if necessary.
In HypnosisViewController.h, let the HypnosisViewController know it conforms to the UIAccelerometerDelegate protocol.
@interface HypnosisViewController : UIViewController <UIAccelerometerDelegate>
In HypnosisViewController.m, override the method viewWillAppear: to get a pointer to the accelerometer and set its update interval and delegate.
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; NSLog(@"Monitoring accelerometer"); UIAccelerometer *a = [UIAccelerometer sharedAccelerometer]; // Receive updates every 1/10th of a second. [a setUpdateInterval:0.1]; [a setDelegate:self]; }
When the HypnosisViewController’s view is moved off screen, the accelerometer updates become unnecessary, and you should set the accelerometer’s delegate to nil. Setting the UIAccelerometer delegate to nil stops the updates to the controller and powers down the accelerometer hardware to conserve battery life. Make this change in HypnosisViewController.m:
- (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [[UIAccelerometer sharedAccelerometer] setDelegate:nil]; }
18.118.253.223