Of the framework called core motion provided by apple, Use a pedometer that handles the number of steps. Official Document
It's like a memorandum because I stumbled unexpectedly. I'm a beginner in swift so please let me know if I make a mistake: flushed:
It seems that there used to be CM Step Counter. It seems to be deprecated now, so I will use CMPedometer.
--Import CoreMotion ... Before that, add the CoreMotion framework on the screen that appears when you click the project name.
--Write to Info.plist
Add a line where appropriate
Key to Privacy --Motion Usage Description
,
Enter the intended use for Type as String and Value.
This is the one who asks if you want to use it when you use it for the first time.
Without this, somehow a crash will occur and an error will occur.
ViewController.swift
let pedometer = CMPedometer()
//Whether CM Peometer is available
if CMPedometer.isStepCountingAvailable() {
//measurement
pedometer.startUpdates(from: Date(), withHandler: {(pedometerData, error) in
if let e = error {
print(e.localizedDescription)
return
}
guard let data = pedometerData else {
return
}
let step = data.numberOfSteps
DispatchQueue.main.async {
label.text = "\(step)Ayumu"
}
})
}
//When you want to finish
pedometer.stopUpdates()
It seems that a problem will occur unless CMPedometer ()
is made a member variable.
isStepCountingAvailable
First check if the CMP recorder is available on your device
Returns as a Bool value
When I look it up, I see startPedometerUpdatesFromDate
,
Said not Xcode: disappointed_relieved:
startUpdates documentation document of startPedometerUpdatesFromDate
I think it's probably the difference between using NSDate and Date as arguments.
NSDate seems to be deprecated, so use startUpdates
which uses Date.
Method to get the number of steps in the past specified period Document for queryPedometerData
startUpdates
can get the data from the specified date and time in the past to the present.
Since you can get the time at that time when you declare the Date ()
method
This is passed to the first argument as the time to start measuring
Pass CMPedometerHandler
as the second argument.
I'm writing {(pedometerData, error) in processing}
.
Document of CMPedometerHandler
DispatchQueue.main.async When displaying the number of steps on the label, it seems that it will be delayed unless asynchronous processing is performed on the main thread, so this is done. (... I still feel that the display is slow: thinking :)
CMPedometerData In addition to the number of steps, you can get various information such as estimated distance traveled, pace of travel, and number of steps climbed stairs with CMPedometer. Data that can be acquired by CM Peometer
I was confused because I could or couldn't use something similar, so I summarized it. There seems to be another one using HealthCare: zipper_mouth:
https://faboplatform.github.io/SwiftDocs/4.coremotion/003_coremotion/ https://teratail.com/questions/90251
Recommended Posts