Retrieve Device Motion data only once - Core Motion

I'm using Core Motion to see if the phone is facing upwards or downwards, and I only need to retrieve the data once. Here is some of my code:

Code Block swift
let manager = CMMotionManager()
manager.showsDeviceMovementDisplay = true
// "Pull data" - since I only need it once
manager.deviceMotionUpdateInterval = 1.0 / 60.0
manager.startDeviceMotionUpdates(using: .xMagneticNorthZVertical)
// Repeats set to false since I only need it once - but same problem even when set to true
self.timer = Timer(fire: Date(), interval: 1.0 / 60.0, repeats: false) { _ in
print("Timer started")
if let motionData = manager.deviceMotion?.gravity.z {
print("Successfully unwrapped")
if 0.7...1 ~= motionData { // Facing downwards
print("Facing downwards")
position = .downwards(motionData)
} else if -1...(-0.7) ~= motionData { // Facing upwards
print("Facing upwards")
position = .upwards(motionData)
} else {
print("Position uknown")
position = .unknown
}
}
}
RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.default)

However, I never reach "Successfully unwrapped". From my attempts to debug, I found that manager.isDeviceMotionActive is never set to true, even though I called startDeviceMotionUpdates(using: .xMagneticNorthZVertical). Why could that be?


Answered by theepicapple in 648924022
It seems like Paul from Hacking with Swift has come once again to save the day - just found his article on how to detect whether the device is facing upwards or downwards through a notification!
(can't post the link, Apple, or at least the forum text editor, doesn't seem to like it)
Accepted Answer
It seems like Paul from Hacking with Swift has come once again to save the day - just found his article on how to detect whether the device is facing upwards or downwards through a notification!
(can't post the link, Apple, or at least the forum text editor, doesn't seem to like it)
Retrieve Device Motion data only once - Core Motion
 
 
Q