ios - How to get accelerometer data outside function? -


i x, y, z accelerometer data inside function.

how these values outside (i'm using real device, iphone 4)?

import coremotion //... var ax: double? var ay: double? var az: double?  if motionmanager.accelerometeravailable {             self.motionmanager.startaccelerometerupdatestoqueue(nsoperationqueue()) {             (data, error) in             dispatch_async(dispatch_get_main_queue()) {                 var ax = data.acceleration.x                 var ay = data.acceleration.y                 var az = data.acceleration.z             }         }      } else {         println("accelerometer not available")     }  println("\(ax)") // nil value 

this second version, same result (which 1 better, if there is? need data of accelerometer in background , foreground):

import coremotion //... var ax: double? var ay: double? var az: double?  if motionmanager.accelerometeravailable {         let queue = nsoperationqueue()         motionmanager.startaccelerometerupdatestoqueue(queue, withhandler: {(data: cmaccelerometerdata!, error: nserror!) in              var ax = "\(data.acceleration.x)"             var ay = "\(data.acceleration.y)"             var az = "\(data.acceleration.z)"             }         )      } else {         println("accelerometer not available")     }  println("\(ax)") // nil value 

the ax variable nil because redefine ax, ay, az in handler. also, handler called after main functions ends, print() statement called before receiving data accelerometer. you'll need refactor code take consideration, maybe updating ui in handler.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -