Swift iOS 9 iPhone Accelerator Application

Open Xcode and select Create a new Xcode project.

Welcome to Xcode

Welcome to Xcode

Select Single View Application and click Next.

Single View Application

Single View Application

For product name, use IntellijSwiftAccelerator and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices. Click Next.

P.S: Don’t forget to untick Include Unit Tests and Include UI Tests.

Open Main.storyboard. Set to Compact Width | Any Height.

Compact Width | Any Height

Compact Width | Any Height

Ctrl + Drag from the Label to the File’s Owner and make the connection with the corresponding properties.

Accelerator ViewController

Accelerator ViewController

Create a new ViewController.

Cocoa Touch Class

Cocoa Touch Class

UIViewController

UIViewController

Then make sure you attach this file into view controller in Identity inspector.

Identity inspector -UIViewController

Identity inspector -UIViewController

The other properties are needed to update the Labels with the axes values. Go to ViewController.swift and add 3 UILabels to the main View.

Outlet – xAxis

Outlet – xAxis

Outlet – yAxis

Outlet – yAxis

Outlet – zAxis

Outlet – zAxis

Open AcceleratorViewController.swift and update the with this code.

import UIKit
import CoreMotion

class AccelerometerViewController: UIViewController {

    var motionManager: CMMotionManager = CMMotionManager()
    @IBOutlet weak var xAxis: UILabel!
    @IBOutlet weak var yAxis: UILabel!
    @IBOutlet weak var zAxis: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.motionManager.accelerometerUpdateInterval = 1;
        
        if (self.motionManager.accelerometerAvailable)
        {
            self.motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) {
                (data, error) in
                dispatch_async(dispatch_get_main_queue()) {
                    self.xAxis.text = String(data!.acceleration.x)
                    self.yAxis.text = String(data!.acceleration.y)
                    self.zAxis.text = String(data!.acceleration.z)
                }
            }
            
        } else {
            print("not active")
        }
    }
}

Leave a Reply

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