How do I retrieve accelerometer data correctly with Swift in iOS?

前端 未结 2 1032
栀梦
栀梦 2021-02-04 17:34

I am trying to record the data from the iPhone\'s accelerometer (my own iPhone 5s) and set a label on the screen to that data using String(format: \"%.2f\", data) w

相关标签:
2条回答
  • 2021-02-04 18:26

    you can get value of x or y or z and print alert of value you want

    motionManager.accelerometerUpdateInterval = 5.0
    motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { (data, error) in
            if let myData = data{
                print(myData)
                if myData.acceleration.y < -0.2{
                    let alert = UIAlertController(title: "Message ", message: "new text", preferredStyle: UIAlertControllerStyle.alert)
                    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                    self.present(alert, animated: true, completion: nil)
    
                }
            }
    }
    
    0 讨论(0)
  • 2021-02-04 18:29

    NSHipster has a good article to talk about the core motion: http://nshipster.com/cmdevicemotion/

    A better way to regularly update UI with motion data is to use the patter as shown in below:

    if manager.accelerometerAvailable {
         manager.accelerometerUpdateInterval = 0.1
         manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) {
         [weak self] (data: CMAccelerometerData!, error: NSError!) in
              accelX.text = String(format: "%.2f", data.acceleration.x)
         }
    }
    
    0 讨论(0)
提交回复
热议问题