← Back to Tutorials

7. Sensors & Hardware

Sensors & Hardware

Accelerometer and Gyroscope

Core Motion provides access to device motion sensors:

import CoreMotion

let motionManager = CMMotionManager()

if motionManager.isAccelerometerAvailable {
    motionManager.accelerometerUpdateInterval = 0.1
    motionManager.startAccelerometerUpdates(to: .main) {
        data, error in
        guard let data = data else { return }
        print("x: \(data.acceleration.x)")
    }
}

if motionManager.isGyroAvailable {
    motionManager.startGyroUpdates(to: .main) {
        data, error in
        guard let data = data else { return }
        print("Rotation: \(data.rotationRate)")
    }
}

Camera

Use UIImagePickerController or AVFoundation to access the camera:

// UIImagePickerController
let picker = UIImagePickerController()
picker.sourceType = .camera
picker.delegate = self
present(picker, animated: true)

// UIImagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
    if let image = info[.originalImage] as? UIImage {
        // Use the captured image
    }
    dismiss(animated: true)
}

Core Location

Request user location with CLLocationManager:

import CoreLocation

let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()

// Delegate
func locationManager(_ manager: CLLocationManager,
    didUpdateLocations locations: [CLLocation]) {
    guard let loc = locations.last else { return }
    print("Lat: \(loc.coordinate.latitude), Lon: \(loc.coordinate.longitude)")
}
Privacy: iOS requires explicit user permission for camera, location, and motion data. Add purpose strings to Info.plist for each capability.

Face ID & Touch ID

Local Authentication framework provides biometric authentication:

import LocalAuthentication

let context = LAContext()
var error: NSError?

if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
    error: &error) {
    context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
        localizedReason: "Unlock the app") { success, error in
        if success {
            print("Authenticated!")
        }
    }
}
Practice Task: Build a "Motion Logger" app that displays real-time accelerometer data. Add a button to capture a photo using the camera. Display the photo and overlay the current GPS coordinates. Protect the app with Face ID authentication on launch. Add all required Info.plist permission descriptions.