iOS 10中的CMPedometer

时间:2016-07-16 16:05:38

标签: ios swift swift3 ios10

我试图访问iOS 10中的CMPedometer数据,并且我已经按照一些教程进行操作,但我似乎无法获得任何工作。我从来没有试过访问这些信息,所以不知道从哪里开始。我喜欢帮助设置一些东西。我们将非常感谢您提供的任何帮助。

我想同时进行实时更新,并且只能在同一天内访问信息。

目前尚未打开并打印出大量错误。

import UIKit
import CoreMotion

class ViewController: UIViewController {

var days:[String] = []
var stepsTaken:[Int] = []

let activityManager = CMMotionActivityManager()
let pedoMeter = CMPedometer()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let cal = Calendar.current
    var comps = cal.components([.year, .month, .day, .hour, .minute, .second], from: Date())
    comps.hour = 0
    comps.minute = 0
    comps.second = 0
    let timeZone = TimeZone.system
    cal.timeZone = timeZone

    let midnightOfToday = cal.date(from: comps)!

    if(CMPedometer.isStepCountingAvailable()){

        self.pedoMeter.startUpdates(from: midnightOfToday) { (data: CMPedometerData?, error) -> Void in
            DispatchQueue.main.async(execute: { () -> Void in
                if(error == nil){
                    print("\(data!.numberOfSteps)")
                    //self.step.text = "\(data!.numberOfSteps)"
                }
              })
           }
       }

    }
}

我一直在玩一些东西,并意识到如果模拟器打开,也会出现一条大错误信息。但是,如果它仅在我的手机上关闭并运行,则错误为:

2016-07-16 18:13:38.054710 test [419:37870] [access] private

1 个答案:

答案 0 :(得分:8)

您使用的是Xcode的测试版,该日志对所有用户都是通用的。没什么可担心的。编辑你的代码lil bit。

import UIKit
import CoreMotion

class ViewController: UIViewController {

    var days:[String] = []
    var stepsTaken:[Int] = []

    let activityManager = CMMotionActivityManager()
    let pedoMeter = CMPedometer()

    override func viewDidLoad() {
        super.viewDidLoad()

        let cal = Calendar.current
        var comps = cal.components([.year, .month, .day, .hour, .minute, .second], from: Date())
        comps.hour = 0
        comps.minute = 0
        comps.second = 0
        let timeZone = TimeZone.system
        cal.timeZone = timeZone

        let midnightOfToday = cal.date(from: comps)!

        #if arch(i386) || arch(x86_64) && os(iOS)

            // Simulator

        #else

            // Run only in Physical Device, iOS

            if(CMPedometer.isStepCountingAvailable()){

                self.pedoMeter.startUpdates(from: midnightOfToday) { (data: CMPedometerData?, error) -> Void in
                    DispatchQueue.main.async(execute: { () -> Void in
                        if(error == nil){
                            print("\(data!.numberOfSteps)")
                            //self.step.text = "\(data!.numberOfSteps)"
                        }
                    })
                }
            }
        #endif
    }
}

Privacy - Motion Usage Description中添加密钥info.plistString值为YES

尝试在iPhone中再次运行该应用并检查。