Swift Components Tour – Accelerometer

In this lesson

This last chapter of the Swift Components Tour is iconic accelerometer! As just a small part of the CoreMotion framework, see how to give your device a meaningful tilt.

Kyle Roberts
Swift Guru at Large

Kyle's Series


Tap on time to skip ahead


Hi, this is Kyle with Brax.tv and we’re finally here on the last stop of the Swift Components Tour. I’m regretting to let you know this, but we are actually in a different universe. That’s right. We went from the universe on a Mac and now we are stuck in a Generation One iPad Mini. Things are looking slightly fuzzy, not quite the beautiful resolution we know and love. But it’s time to talk Swift. Here we are on the last stop titled Accelerometer. The Accelerometer is actually just a small part of the CoreMotion framework, but I wanted to include the Accelerometer here because it is like a landmark thing for iOS. A lot of the first iOS games that use the Accelerometer – it seemed like a big thing when I had an iPod Touch way back when. It’s maybe not as popular now but it’s always worth learning about. So let’s talk about what’s going on on this screen.


We have X, Y and Z labels, each with a value label underneath. A little bit of something something going on at the bottom, but that’s a surprise. My iPad is sitting on my desk right now, I’m going to pick it up and we’re going to see these value labels go wild. That’s because this is the Accelerometer reporting the X, Y and Z rotation values with the gyroscope in real time. I’m just displaying those values on these value labels so that you can see sort of what’s happening.


Something I’ve learned doing this, that we can talk about in a little bit, is that using the Accelerometer itself resulted in values that were a lot shakier and a lot more wild than this. You can actually use the Accelerometer and gyroscope together to report a lot more smooth values. I’m going to sort of rotate my device in front of me and you can see the Y value is slowly getting smaller and smaller into the negative numbers and then back to 0 as I flip it upside down. While the X and Z labels stayed fairly close to -1 and 1. It’s just something cool and there’s not normally many implementations of the Accelerometer in apps that aren’t games. But there surely are some good ideas out there. I don’t have any right now except this one that we’re going to talk about in a second.


But above that is this Zero button, which you can’t see where my thumb is hovering over but it’s hovering right over the Zero button. That’s sort of like a calibration button. I’m going to tip my iPad so that none of the numbers are close to zero, or at least as far from zero as I can get them. The X value is being a little tough to work with. They’re all sort of around -0.5 or 0.5 and then I’ll press the Zero button and they’re all zeroed out to zero. It’s sort of like we’ve reached a new, let’s call it, home base. And then as we rotate the iPad from that point, I’m going to rotate it forward, we can see that the Z value got a lot bigger. I’ll press the Zero button again and then rotate it backwards and now the Z value is getting a lot smaller. I know it’s tough to see in real time, but I’m having to use my iPad since the iOS simulator on a Mac does not have the Accelerometer. But I think this is working out great, it’s fun. I’m going to zero it out again, hold my iPad as steady as possible, and then flip the enable FUNctionality switch. Are you ready? Three, two, one.


The screen changed color. I’m just flopping my iPad around, we’re getting different colors. Basically what I did was hook the X, Y and Z values up to the R, G and B values of a UIColor. On each update of the Accelerometer I am basically setting the background color to match that. Pretty cool, huh? I think this is all we’ll need from my iPad so let’s hop into the code in this alternate universe called a Mac.


We’re back in a much more familiar world, Xcode. For now, we’re going to skip the storyboard part of the tour because there’s nothing interesting going on. It’s exactly as we saw it without the FUNctionality switch on in the app. The three X, Y, Z labels, the three X, Y, Z value labels, the Zero button, or the calibration button, and then the functionality switch and label. Here we have references to the X, Y, Z value labels and the FUNctionality switch. Some other properties here, one called motion manager, which is an instance of CMMotionManager class. Sadly, this isn’t going to be a walk through of how to use the CoreMotion framework, or how to implement any of the fun stuff like the gyroscope or the Accelerometer. This is just going to be a very general example of how I’m using it in this dinky little app. We also have a property for an NSNumberFormatter and then an object for CMAcceleration called calibratedAcceleration. We’ll get to the purpose of that in a second.


In viewDidLoad we just have a little bit of setup for the number formatter. Then we’re asking the motion manager if deviceMotionAvailable. That’s why we had to use a physical iPad because it has the hardware that CoreMotion uses for it’s functionality and what was made for. Sadly, the simulator does not even have any simulation of that. If you run this view controller in the simulator nothing is going to happen. You can flip the functionality switch, I think the screen might turn blue. That’s not very fun, there’s not FUNctionality in there. It’s just a blue screen. But if it is, we’re going to set up the device motion monitoring. Before we get to that method down here in viewWillDisappear, we’re going to turn off the device motion updates. So once we leave this view controller this motion manager instance is not going to keep tracking the accelerometer even when you’re not on this screen. We just want to make sure that we’re only monitoring this device motion stuff on the screen.


One thing to point out that the device motion title is actually a title for using the gyroscope and the Accelerometer together to get those more stable and smooth  X, Y and Z value changes that we were talking about when we had the app open. You can also just use the gyroscope or the Accelerometer by themselves for different purposes. For this, using both at the same time provided with some better readings.


To set up device motion monitoring, we’re again checking if the device motion is available. If so, we’re going to set the device motion update interval to 0.01 seconds. That means that every 100th of a second, so 100 times a second, it’s going to report the current readings from the hardware to the motion manager here. Up to 100 times a second you’ll see the values changing as you rotate your device around if you’re running this app on your device. Here with the motionManager instead of using delegates or target action methods, we actually are getting the reports from the motion manager about changes in the motion values to this block here which we are running on the main queue. What we get from this is a data object, which is a CMDeviceMotion instance and then an error object. Just for this example I’m not worrying about the error. During the development of this I never ran into any errors, not saying that you shouldn’t at least check for errors in your app. NSErrors are a whole other discussion.


What we’re taking here, is we’re going to set each of the X, Y and Z value labels to the data.gravity.value to the CMDeviceMotion’s property gravity values for X, Y and Z. The gravity property is just an instance of CMAcceleration where it is recording the values for the gyroscope and the Accelerometer combined. Getting a little bit ahead of ourselves for this calibration stuff, is we will take the calibrated CMAcceleration values from our local instance of that so that if we have calibrated the accelerometer we can do the math to find the adjusted values here.


Below that I’m just checking that the functionality switch is on. If it is then we’ll call this method setBackgroundWithCalibration. The other thing that’s going on there is we are animating over the duration of the motion update interval, which we set up here, to set the background color to the absolute value of the motion manager’s device motion gravity values and casting them to a CGFloat so we can use them in this init method of UIColor.


As a positive number, if you increase the X value of the device motion or decrease, as long as it is under zero, then we will slowly add more red into this RGB color. And so on with green and blue. Back to the calibration, when we tap the Zero button we are going to store the current device motion values from the device’s hardware into this local property that I’ve called calibratedAcceleration so that when we are up here and setting the value labels to the correct values we can take into account where we wanted to zero out the X, Y and Z values and take into account the current value with the calibrated value to get our value for display. I hope all that made sense. It’s one of the more complicated things we’ve worked through on this tour.


And even though the tour is technically over, we’ve reached the last stop, stay tuned for some more. In the future we’ll be going over stuff like Interface Builder, how to use it and how to use it with a view controller. Getting into navigation a little bit or about dates that we’ve been running into a lot through this tour. And maybe we’ll run into a few new stops along the way. See you next time and thanks for watching.

Additional Info

Register to get access to additional resources and info.