Lesson 5. iOS Sensors Overview

In this lesson you'll learn about iOS sensors.

Activity Type Lesson
Expected Duration 30 minutes
Topic iOS Sensors Overview
Objective Learn about iOS sensors.

1. Core Motion

As seen on Apple Developer

Core Motion is a framework that reports motion-related data from the sensors in the hardware to your app. Many services of the frameworl let you access both raw values and the processed version of them, depending on your needs.

Here's the overview of all the sensors included in the framework:

Sensor Common Uses
Accelerometer Accelerometer data for all three axis
Gyroscope Raw gyroscope data
Pedometer Step-counting data
Magnetometer Compass-level orientation
Altitude Altitude based on barometric information
Historical Data Recorded motion events to help you analize movement patterns

2. First Steps

Using a CMMotionManager is the object you use to start services that report any change in the available sensors.

To get started, import the Core Motion framework into your project:

import CoreMotion

Now you need to create a new instance of CMMotionManager, which will let you obtain four types of motion: raw accelerometer data, raw gyroscope data, raw magnetometer data, and processed device-motion data (which includes accelerometer rotation-rate, and attitude measurements).

let motionManager = CMMotionManager()

And depending on which sensor we want to implement, we call:

 override func viewDidLoad() {
     super.viewDidLoad()
     //...
     motionManager.startAccelerometerUpdates() //or
     motionManager.startGyroUpdates() //or
     motionManager.startMagnetometerUpdates() //or
     motionManager.startDeviceMotionUpdates()
 }

Now that the sensors are active, you need to handle their updates:

 @objc func update() {
     if let accelerometerData = motionManager.accelerometerData {
            print(accelerometerData)
        }
        if let gyroData = motionManager.gyroData {
            print(gyroData)
        }
        if let magnetometerData = motionManager.magnetometerData {
            print(magnetometerData)
        }
        if let deviceMotion = motionManager.deviceMotion {
            print(deviceMotion)
        }
 }

And if we want to change the request interval to 3 seconds, we need to provide the update interval to the block handler:

 override func viewDidLoad() {
     /...
     timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
 }

3. Location Services and GPS

Location awareness is one of the unique features of mobile applications. iOS offers a Location framework that helps you optimize your work and offers several nice features to play with. This framework is called CoreLocation.framework.

To get started, you need to import the framework:

import CoreLocation

Now you need to add the variables needed to store and obtain the location.

import CoreLocation
//...
class MainViewController: UIViewController, CLLocationManagerDelegate {
    var locationManager: CLLocationManager = CLLocationManager()
    var userLocation: CLLocation!
}

Next, we need to initialize the location handler and configure some parameters such as precision:

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
    userLocation = nil
}

And now that we are ready to get the device location, we must implement the callback handler and the error handler:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let latestLocation: CLLocation = locations[locations.count -1]
    if (userLocation == nil) {
        userLocation = latestLocation
    }
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    //Do something with the error
}

All the data from the Location Sensor can be placed on a map by using the Map Object. Visit Google Maps API to learn more about it.

If you run your project, you'll get an error because of missing permitions. You must then add the following key to your info.plist:

NSLocationWhenInUseUsageDescription

That's it !

4. Using Google Maps

  1. Install the pod

To use Google Maps in Swift you need to install the pod from CocoaPods. The Podfile should include:

pod 'GoogleMaps'
  1. Get an API Key

To use the Google iOS SKD, you'll need an API Key. To the generate the key, visit Google API Console.

Then go to your AppDelegate.swift class and import GoogleMaps. Then copy the following code to application(_:didFinishLaunchingWithOptions:):

GMSServices.provideAPIKey("YOUR_API_KEY")

  1. Add a map

Visit your UIViewController (where you want to add the map). Create a custom UIView with the size you need. Don't forget to connect the delegate.

Now, in the UIViewController and write the following code:

import UIKit
import GoogleMaps

class ViewController: UIViewController {

    @IBOutlet fileprivate weak var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let camera = GMSCameraPosition.camera(withLatitude: 37.36, longitude: -122.0, zoom: 6.0)
        mapView.camera = camera
        showMarker(position: camera.target)
    }

    func showMarker(position: CLLocationCoordinate2D){
        let marker = GMSMarker()
        marker.position = position
        marker.map = mapView
    }
}
extension ViewController: GMSMapViewDelegate{

}

After you run your app, you should get the following results:


Version Author Date
1.0 Juan Santiago Acevedo February 24, 2018

results matching ""

    No results matching ""