0

Trying to implement this raywenderlich tutiorial in swift , but unfortunately I am

  fatal error: unexpectedly found nil while unwrapping an Optional value

on line

    let acceleration :CMAcceleration = self.motionManager!.accelerometerData.acceleration

Can any body please help why its occuring

please down scene file from here

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
Ali
  • 10,774
  • 10
  • 56
  • 83

1 Answers1

0

self.motionManager is nil and you try to unwrap a nil value.Always unwrap optional values by checking for nil with optional binding or use optional chaining.

if let motionManager = self.motionManager {
   if let accelerometerData = motionManager.accelerometerData {
      let acceleration :CMAcceleration = accelerometerData.acceleration
   }
 }
 else {
   print("motion manager is nil")
 }

You should check your code if you have intialized motionManager or not.

EDIT

I have checked documentation

Returns the latest sample of accelerometer data, or nil if none is available. */

var accelerometerData: CMAccelerometerData! { get }

So you need to also check nil for accelerometerData.It can be nil and it is Implicitly wrapped optional so it will crash when data not available.

codester
  • 36,891
  • 10
  • 74
  • 72