How to get accelerometer data in IOS?

前端 未结 6 2055
被撕碎了的回忆
被撕碎了的回忆 2021-02-08 09:58

I am using the UIAccelerotmeterDelegate method accelerometer:didAccelerate: but recently that method has been deprecated in iOS 5.0. So what is the alternative way

6条回答
  •  甜味超标
    2021-02-08 10:03

    I am answering this for Swift 5.x.

    @available(iOS, introduced: 2.0, deprecated: 13.0, message: "UIAcceleration has been replaced by the CoreMotion framework") public protocol UIAccelerometerDelegate : NSObjectProtocol { }

    Don't conform to UIAccelerometerDelegate and add only CoreMotion framework.

    import CoreMotion
    

    If you want to show animation or create game , you can start with following code.

    self.motionManager = CMMotionManager()
    self.motionManager?.startAccelerometerUpdates()
    if motionManager.isAccelerometerAvailable {          
      motionManager.startAccelerometerUpdates(to: .main) { (data, error) in
        if let myData = data {
            let x =  String(format: "%.3f",myData.acceleration.x)
            let y =  String(format: "%.3f",myData.acceleration.y)
            let z =  String(format: "%.3f",myData.acceleration.z)
        DispatchQueue.main.async { 
              var rect = self.anyObject.frame
             let movetoX = rect.origin.x + CGFloat(myData.acceleration.x * stepMoveFactor)
             let movetoY = rect.origin.y - CGFloat(myData.acceleration.y * stepMoveFactor)
             if ( movetoX > 0 && movetoX < SCREEN_WIDTH ) {
                rect.origin.x += CGFloat(myData.acceleration.x * stepMoveFactor)
             }
             if ( movetoY > 1 && movetoY < maxY ) {
               rect.origin.y -= CGFloat(myData.acceleration.y * stepMoveFactor) }
             }
        }
     }
    

    }

    use UIView.animate if you want. This method initiates a set of animations to perform on the view. The block object in the animations parameter contains the code for animating the properties of one or more views.

提交回复
热议问题