Reputation: 167
I am using AVAudioPlayer to play a sound. The sound is played after I check movement from the accelerometer. Everything works fine. I noticed that the output from println() periodically shows repeated character. Here is the code to output to the console:
motionManager.accelerometerUpdateInterval = (1/40)
motionManager.startAccelerometerUpdatesToQueue(queue) { accelerometerData, error in
var x = accelerometerData.acceleration.x
if x > 0.75 {
println("X is greater than 0.5: \(accelerometerData.acceleration.x)")
if !self.audioPlayer.playing {
self.toggleAVPlayer()
}
}
And here is a sample from the console:
X is greater than 0.5: 0.767669677734375
X is greater than 0.5: 1.41529846191406
XX iiss ggrreeaatteerr tthhaann 00..55:: 20..2824260008041529240772063516
2
X is greater than 0.5: 2.65106201171875
Why is the call to println() giving repeated characters?
Upvotes: 1
Views: 113
Reputation: 42325
What's happening is that the accelerometer is posting updates to your queue fast enough for the queue to run some updates concurrently and your print statements are overlapping. The easiest way to fix that is to simply dispatch your println
back to the main queue:
motionManager.accelerometerUpdateInterval = (1/40)
motionManager.startAccelerometerUpdatesToQueue(queue) { accelerometerData, error in
var x = accelerometerData.acceleration.x
if x > 0.75 {
dispatch_async(dispatch_get_main_queue()) {
println("X is greater than 0.5: \(accelerometerData.acceleration.x)")
}
if !self.audioPlayer.playing {
self.toggleAVPlayer()
}
}
I'd be careful though, the docs say:
Because the processed events might arrive at a high rate, using the main operation queue is not recommended.
You shouldn't keep that println
in there except for when you need to debug just that data. You might also want to think about only printing every 10th or 100th update or something.
Upvotes: 2