Search code examples
iosswiftxcodeswift3ios10

How to detect if iPhone is in motion?


I am trying to create an app (in swift) that will detect if a iPhone is in motion.

How would I go to approaching this?


Solution

  • You should look into getting the data from the accelerometer.

    Here is an example of, how you could retrieve the information.

    let motionManager = CMMotionManager()
    if motionManager.isAccelerometerAvailable {
      let queue = OperationQueue()
      motionManager.startAccelerometerUpdates(to: queue, withHandler:
        {
          data, error in guard let data = data else { return }
          print("X = \(data.acceleration.x)")
          print("Y = \(data.acceleration.y)")
          print("Z = \(data.acceleration.z)")
        }
      )
    } else {
      print("Accelerometer is not available")
    }
    

    Dont forget to import CoreMotion!

    Updated solution Here is a working example of how to get the accelerometer data, if the device is moving with over 10 km/h.

    import UIKit
    import CoreMotion
    import CoreLocation
    
    class ViewController: UIViewController {
    
    var timer = Timer()
    var locationManager = CLLocationManager()
    let motionManager = CMMotionManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        scheduledTimerWithTimeInterval() //Calling function with timer
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    func scheduledTimerWithTimeInterval(){
        // Scheduling timer to Call the function **getSpeed** with the interval of 1 seconds
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.getSpeed), userInfo: nil, repeats: true)
    }
    
    
    func getSpeed(){
        
        var speed: CLLocationSpeed = CLLocationSpeed()
            speed = Double((locationManager.location?.speed)!)
        
            print(String(format: "%.0f km/h", speed * 3.6)) //Current speed in km/h
        
        //If speed is over 10 km/h
        if(speed * 3.6 > 10 ){
            
            //Getting the accelerometer data
            if motionManager.isAccelerometerAvailable{
                let queue = OperationQueue()
                motionManager.startAccelerometerUpdates(to: queue, withHandler:
                    {data, error in
                        
                        guard let data = data else{
                            return
                        }
                        
                        print("X = \(data.acceleration.x)")
                        print("Y = \(data.acceleration.y)")
                        print("Z = \(data.acceleration.z)")
                        
                    }
                )
            } else {
                print("Accelerometer is not available")
            }
        
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    }