Writing a Magnetometer Application

Let’s go ahead and implement a simple view-based application to illustrate how to use the magnetometer. Open Xcode and start a new iPhone project, select a View-based Application template, and name the project “Compass” when prompted for a filename.

Since you’ll be making use of the Core Location framework, the first thing you need to do is add it to our new project. Click on the Compass project file in the Project navigator window on the right in Xcode, select the Target and click on the Build Phases tab, click on the Link with Libraries drop down and click on the + button to open the file pop-up window. Select CoreLocation.framework from the list of available frameworks and click the Add button.

You’re going to build an application that will act as a compass, so you’re going to need an image of an arrow to act as the compass needle. Download or draw in the graphics package of your choice, an image of an arrow pointing upwards on a transparent background. Save or convert it to, a PNG format file. Drag-and-drop this into the Xcode Project, remembering to tick the “Copy items into destination group’s folder (if needed)” check box in the pop up dialog that appears when you drop the files into Xcode.

Click on CompassViewController.xib file to open it in Interface Builder. Drag and drop a UIImageView from the Object Library into the View, positioning it roughly in the center of your window, resizing the bounding box to be a square, as in Figure 5-3. In ...

Get Basic Sensors in iOS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.