iOS Motion Detection: Motion Detection Sensitivity Levels

后端 未结 4 1490
我在风中等你
我在风中等你 2021-02-05 18:24

I have a simple question. I\'m trying to detect when a user shakes the iPhone. I have the standard code in place to detect the motion and this works no problem. However, in test

4条回答
  •  甜味超标
    2021-02-05 18:47

    Heres how I did this using Swift 3.

    Import CoreMotion and create an instance

    import CoreMotion
    let motionManager = CMMotionManager()
    

    On ViewDidLoad or wherever you want to start checking for updates:

     motionManager.startDeviceMotionUpdates(to: OperationQueue.current!, withHandler:{
                deviceManager, error in
                if(error == nil){
                    if let mgr = deviceManager{
                        self.handleMotion(rate: mgr.rotationRate)
                    }
                }
            })
    

    This function takes the rotation rate and gets a sum for the absolute values for x,y and z movements

      func handleMotion(rate: CMRotationRate){
            let totalRotation = abs(rate.x) + abs(rate.y) + abs(rate.z)
    
            if(totalRotation > 20) {//Play around with the number 20 to find the optimal level for your case
                start()
            }else{
           print(totalRotation)
            }
        }
    
    func start(){
    
    //The function you want to trigger when the device is rotated
    
    }
    

提交回复
热议问题