Yes, I have seen a previous question on this, but I still can't get this to work. My previous Swift2 code was...
motionMgr.startDeviceMotionUpdatesToQueue(NSOperationQueue(), withHandler: handleMove)
which called:
func handleMove(motion: CMDeviceMotion?, error: NSError?) {
...
}
This has changed under Swift3, and now the startDeviceMotionUpdatesToQueue
uses a closure. I can't for the life of me figure out how to call my existing method. I realize the NSError
became Error
and other minor changes, but the syntax of the call from the closure has me very confused.
This should work for you, there are just a few re-namings in Swift 3.
motionMgr.startDeviceMotionUpdates(to: OperationQueue(), withHandler: handleMove)
func handleMove(motion: CMDeviceMotion?, error: Error?) {
// ...
}
The handler
is of type CMDeviceMotionHandler
which is defined as a typealias
to a closure:
typealias CMDeviceMotionHandler = (CMDeviceMotion?, Error?) -> Void
We just need to provide a closure (or a function, since a function is a closure), that takes in two parameters (a CMDeviceMotion?
and Error?
) and returns nothing (Void
).
Alternatively, you could provide a closure instead of a function like so:
motionMgr.startDeviceMotionUpdates(to: OperationQueue(), withHandler: { deviceMotion, error in
// ...
})
or use the new trailing closure syntax:
motionMgr.startDeviceMotionUpdates(to: OperationQueue()) { deviceMotion, error in
// ...
}