[Swift] Get the number of steps with CMP edometer

Get your steps with swift!

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:

stepCount and CMPedometer

It seems that there used to be CM Step Counter. It seems to be deprecated now, so I will use CMPedometer.

Preparation

--Import CoreMotion ... Before that, add the CoreMotion framework on the screen that appears when you click the project name. framework.png

--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.

Write the code!

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

startUpdates and startPedometerUpdatesFromDate

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.

What about queryPedometerData?

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.

About the argument of startUpdates

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:

I used it as a reference

https://faboplatform.github.io/SwiftDocs/4.coremotion/003_coremotion/ https://teratail.com/questions/90251

Recommended Posts

[Swift] Get the number of steps with CMP edometer
[Swift] Get the height of Safe Area
I checked the number of taxis with Ruby
[Swift] How to get the number of elements in an array (super basic)
How to get the ID of a user authenticated with Firebase in Swift
[Swift] How to get the document ID of Firebase
[Swift] Get the timing when the value of textField is changed
Find the number of days in a month with Kotlin
[Java1.8 +] Get the date of the next x day of the week with LocalDate
[Swift5] How to get an array and the complement of arrays
[Swift] Change the textColor of UIDatePicker
[Swift] Get the current time numerically
The basic basis of Swift dialogs
[Swift UI] How to get the startup status of the application [iOS]
Method to add the number of years and get the end of the month
[Abuse strictly prohibited] Get the number of views of your Qiita article
Get the ID of automatic numbering
[swift5] How to change the color of TabBar or the color of item of TabBar with code
Get the value of enum saved in DB by Rails with attribute_before_type_cast
[Java] Get MimeType from the contents of the file with Apathce Tika [Kotlin]
(Note) Get a set of dependent library jars with the help of Gradle
Get the result of POST in Java
Check the contents of params with pry
[Java] Get the day of the specific day of the week
[Swift] Vaguely grasp the flow of Delegate
[Swift 5] Implementation of membership registration with Firebase
[Swift5] Round the acquired image with UIImagePicker
[Swift] Termination of the program by assertion
How to determine the number of parallels
About the treatment of BigDecimal (with reflection)
About the number of threads of Completable Future
[Swift] Change the color of SCN Node
Format the contents of LocalDate with DateTimeFormatter
[Java] Check the number of occurrences of characters
The basic basis of Swift custom cells
[Java] Get the date with the LocalDateTime class
Verify the contents of the argument object with Mockito
[Java] Get the length of the surrogate pair string
Manage the version of Ruby itself with rbenv
Overwrite the contents of config with Spring-boot + JUnit5
The story of tuning android apps with libGDX
[Swift] How to link the app with Firebase
How to get today's day of the week
Calculate the similarity score of strings with JAVA
Get Body part of HttpResponse with Filter of Spring
Find the Fibonacci number with the Fork / Join Framework
Prepare the environment of CentOS 8 with Sakura VPS
Get your version number in the Android app
Specify the default value with @Builder of Lombok
Measure the distance of the maze with breadth-first search
[Java] How to get the authority of the folder
[Swift] Termination of the program by the fatalError function
[Swift] Use Swity JSON to easily get information from JSON data of the fortune-telling API
[JavaScript] I can't get the response body at the time of error with axios (ajax)
Let's implement a function to limit the number of access to the API with SpringBoot + Redis