Search code examples
swiftnsoperationqueue

Error: value of optional type 'NSOperationQueue?' not unwrapped; did you man to use '!' or '?'?


So, I am trying to get data from the accelerometer sensor but I keep getting this error even though I have tried '!' and '?' and 'if let'. I can not think of trying anything else and the strange think is that the same code works on a youtube tutorial from where I got it. Here is the code:

// Instance variables
var currentMaxAccelY: Double = 0.0
var currentMaxAccelZ: Double = 0.0
lazy var motionManager = CMMotionManager()

// functions
override func viewDidLoad() {
currentMaxAccelY = 0.0
currentMaxAccelZ = 0.0

    // Do any additional setup after loading the view.
    //video version
    if (self.motionManager.accelerometerAvailable) {

    self.motionManager.accelerometerUpdateInterval = 0.2
    self.motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()){[weak self](accelerometerData: CMAccelerometerData!, error: NSError!) in //here i get the error
        self.outputAccelerationData(accelerometerData.acceleration)
         if (error != nil){
         print("\(error)")

            }
        }
   }

   else {
        print("accelerometer not available")
    }

    super.viewDidLoad()

}

func outputAccelerationData(acceleration: CMAcceleration){
    jumpCounter?.text = "\(acceleration.z).2fg"
    y?.text = "\(acceleration.y).2fg"
    if fabs(acceleration.y) > fabs(currentMaxAccelY) {
        currentMaxAccelY = acceleration.y
    }
    if fabs(acceleration.z) > fabs(currentMaxAccelZ) {
        currentMaxAccelY = acceleration.z
    }
    yMax?.text = "\(currentMaxAccelY).2f"
    zMax?.text = "\(currentMaxAccelZ).2f"

}

Any help is really appreciated..


Solution

  • It works for me

    let motionManager = CMMotionManager()
    if let queue = NSOperationQueue.currentQueue() {
        motionManager.startAccelerometerUpdatesToQueue(queue) { (data, error) -> Void in }
    }