【问题标题】:Using startDeviceMotionUpdates under Swift 3在 Swift 3 下使用 startDeviceMotionUpdates
【发布时间】:2017-01-05 02:22:31
【问题描述】:

是的,我已经看到了previous question,但我仍然无法让它工作。我之前的 Swift2 代码是...

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

调用:

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

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

【问题讨论】:

    标签: swift3 core-motion


    【解决方案1】:

    这应该对你有用,在 Swift 3 中只有一些重命名。

    motionMgr.startDeviceMotionUpdates(to: OperationQueue(), withHandler: handleMove)
    
    func handleMove(motion: CMDeviceMotion?, error: Error?) {
        // ...
    }
    

    handlerCMDeviceMotionHandler 类型,它被定义为闭包的 typealias

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

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

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

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

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

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

    【讨论】:

    • 谢谢@nathan。对我来说,关键是尾随语法,我发现它更容易理解。我只是将 func 调用放在尾随闭包中,就是这样!
    • motionMgr.startDeviceMotionUpdates(使用:CMAttitudeReferenceFrame.xTrueNorthZVertical,到:OperationQueue()) { deviceMotion,self.handleMove 中的错误(运动:deviceMotion,错误:错误)}
    猜你喜欢
    • 2016-10-17
    • 2017-02-26
    • 2017-03-07
    • 2018-01-15
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    相关资源
    最近更新 更多