swift3 - 在 Swift 3 下使用 startDeviceMotionUpdates

标签 swift3 core-motion

是的,我看到了previous question对此,但我仍然无法让它发挥作用。我以前的 Swift2 代码是...

motionMgr.startDeviceMotionUpdatesToQueue(NSOperationQueue(), withHandler: handleMove)

调用:

func handleMove(motion: CMDeviceMotion?, error: NSError?) {
    ...
}

这在 Swift3 下发生了变化,现在 startDeviceMotionUpdatesToQueue 使用闭包。我一生都无法弄清楚如何调用我现有的方法。我意识到 NSError 变成了 Error 和其他细微的变化,但是闭包调用的语法让我非常困惑。

最佳答案

这应该适合您,Swift 3 中只有一些重命名。

motionMgr.startDeviceMotionUpdates(to: OperationQueue(), withHandler: handleMove)

func handleMove(motion: CMDeviceMotion?, error: Error?) {
    // ...
}

handler 的类型为 CMDeviceMotionHandler,它被定义为闭包的 typealias:

typealias CMDeviceMotionHandler = (CMDeviceMotion?, Error?) -> Void

我们只需要提供一个闭包(或一个函数,因为函数就是一个闭包),它接受两个参数(CMDeviceMotion?Error?)并且什么也不返回(Void)。

或者,您可以提供一个闭包而不是像这样的函数:

motionMgr.startDeviceMotionUpdates(to: OperationQueue(), withHandler: { deviceMotion, error in
    // ...
})

或使用新的尾随闭包语法:

motionMgr.startDeviceMotionUpdates(to: OperationQueue()) { deviceMotion, error in
    // ...
}

关于swift3 - 在 Swift 3 下使用 startDeviceMotionUpdates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41470575/

相关文章:

c# - 如何将 UlImage 作为 Base64 字符串传递到 Asp.Net Web Api

ios - iPhone 用户加速度不为零

ios - 从 iPhone 6 中的气压计收集相对高度

ios5 - 什么取代了 iOS 5 已弃用的加速度计 :didAccelerate?

ios - 在 iOS 的后台持续更新加速度计

ios - 尝试打开Goog​​le Maps URL时无法调用非功能类型UIApplication的值

ios - Core Plot 饼图不显示

iphone - Skype 防抖视频录制背后的技术是什么?

ios - 使用 Alamofire 下载视频,然后在 AV 播放器上播放

ios - Swift 3.0 async Dispatch.global 不运行