28.iPhone陀螺儀傳感器的介紹

繼續上一文章, 這次我們來看看陀螺儀怎麼使用, 其實是和加速度傳感器差不多的, 一樣的調用方法, 下面讓我們來看看代碼

PS: 已經更新到Swift 2.1, 支持iOS 9.1


1.實現代碼

import UIKit
import CoreMotion

class ViewController: UIViewController {

    var cmm: CMMotionManager!

    override func viewDidLoad() {
        super.viewDidLoad()
        // 1.實例化CMMotionManager
        cmm = CMMotionManager()
    }

    override func viewWillAppear(animated: Bool) {
        // 2.設置每秒獲取一次
        cmm.gyroUpdateInterval = 1

        // 3.判斷陀螺儀是否可用
        if cmm.gyroAvailable {
            cmm.startGyroUpdatesToQueue(NSOperationQueue(), withHandler: { (data: CMGyroData?, error: NSError?) -> Void in
                print(data)
            })
        } else {
            print("陀螺儀不可用")
        }
    }

    override func viewDidDisappear(animated: Bool) {
        // 4.判斷傳感器是否正在更新數據
        if cmm.gyroActive {
            // 4.1.如果是, 就停止更新
            cmm.stopGyroUpdates()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

2.最終效果

0


發佈了239 篇原創文章 · 獲贊 8 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章