Read and Write Info in a Swift App

How to read and write Mindful Minutes from iOS's HealthKit with Swift

by Ben Church

How to read and write Mindful Minutes from iOS's HealthKit with Swift

I took the time to figure out how to read and write from HealthKit and so you don't have to!

1*fPKXwxU5RwbLuoSMBJzcBg
Permit me show you what Apple makes hard to detect ?

I admittedly love the road Apple has been going with their iOS SDK's. (Their hardware not so much). Apple tree's focus on security has immune information technology to become a reliable company to trust your sensitive information with. This has allowed iPhones to make headway as the device best suited to host medical data. As a result, they're also the best device to make software that interfaces with a user'southward sensitive personal info.

With this in mind, I believe it'south essential to know how to read and write from Apple'due south HealthKit and so that nosotros every bit developers can leverage the position Apple has put itself in. So today's tutorial is going to focus on Reading and writing Mindful Minutes from Apple'southward HealthKit.

By the cease of this tutorial, you will accept learned how to:

  • Setup a bones iOS app
  • Asking permission to read and write data from HealthKit
  • Read and query data from HealthKit
  • Write data dorsum to HealthKit

Alright let'south jump into setting up the XCode Project. ?

Setup the Skeleton

Every great project starts from the aforementioned screen (if yous're just looking for code, then you can skip this section).

1. Create a new project

Let'due south kick this off by creating a new Single View App project in XCode.

1*2rFbwZuGufTSLI8p_FsJJg
Start by going to File > New > Project
1*HiwauM4djV0kvMcPjrDVPQ
You should be able to exit this all the same with the exception of my name.

ii. Include HealthKit

Once we've created the project, we demand to bundle HealthKit with our application:

1*ZK3RgCV8Z9HBhSiCEU3Org
Include HealthKit into our App

and update the info.plist file to contain what the user will meet when nosotros ask for their permission to access their data.

1*rLBnDDqGFBBeHL7rM0lauA
You need to edit the source lawmaking of this file.

Add together the following xml to the info.plist file:

3. Create a basic UI

To finish up the setup, nosotros will want to create a uncomplicated UI that volition let us to view the data we have read from the HealthKit and provide an activity that volition allow u.s. to trigger a write back to the HealthKit.

Start by opening the storyboard and:

  1. Add a label and connect it to the ViewController.swift file under the proper name mindfulMinuteLabel
  2. Add a button and connect information technology to an Action in the ViewController.swift file titled addMinuteAct
1*-ro1ScwT71pOlvYWM0rJzg
Creating our UI

Breath some life into it…

Now that we've put the infrastructure in place, it'southward time to write the logic that will do all the interfacing with HealthKit we have been talking nigh.

1. Ask for permission

Every HealthKit app needs to explicitly ask for a user'southward permission for every blazon of read and write information technology needs to do. To accomplish this, we desire to ask on viewDidLoad for permission to read Mindful Sessions and for permission to write Mindful Sessions.

Now when the app is run, you should be prompted by the screen below.

If you are running this right at present, you volition want to comment out self.retrieveMindfulMinutes()
1*rFvNSSAw51LOil7bwsVjBA
Our Permission Screen

2. Reading Mindful Minutes

And so far this has been very straight frontward: Create UI, enquire for permission. Next we're going to come into reading from HealthKit. While Apple tree gives us a powerful UI, it's not necessarily intuitive. And so I'm going to begin by showing you the code, and so I'll explain it after.

The query nosotros execute to retrieve our Mindful Sessions can be cleaved into 4 components:

one. Sort by End Date

1*N5vzEO0ua5ZOz7yonHdldA
Get the most recent Sessions

The beginning section of this lawmaking is optional but useful to know. What we are doing is asking the query to give united states the list of Mindful Sessions ordered past their stop time with the well-nigh recent session being first.

2. Utilize the Predicate to define the Query

1*99AbYdyrnCnzwmgeLEQEeA
Expect for all sessions in the terminal 24 hours

The next portion of our code deals with the actual specifics of a "query": What subset of data are nosotros looking for. In our instance, we want all samples from the last 24 hours.

3. Compose and Run your Query

1*avN2Xe7pnlkiypvUN-e7aQ
Run it!

Finally, we desire to combine the sortDescriptor, the predicate, and the sampleType we want from the HealthKit together with the role that will handle whatever is returned by the query (resultsHandler). After this is all equanimous into a HKSampleQuery, the merely stride left is to execute it!

4. Aggregating the session information and updating the UI

Within the part we defined equally our resultsHandler in the previous section, nosotros want to:

  1. Become the total time for each Mindful Session
  2. Sum all total times to get the total number of Mindful minutes over the concluding 24 hours.
  3. Update our characterization with the total.

This should all be relatively straightforward if y'all understand the concepts of map and reduce. If these are new to you, I recommend taking the time to larn them. They are found in most programming languages and are a great introduction into the wonderful world of Functional Programming.

The just piece that may non exist straightforward is why nosotros wrap

                self.meditationMinutesLabel.text = labelText              

in DispatchQueue.main.async . The reason we practice this is and then nosotros tin update the UI without blocking the master thread of the application. This is a convention enforced by the compiler itself!

Writing the information

In the above, nosotros went over how to read from HealthKit. But how do nosotros write data to it? Thankfully the process is a lot simpler. The following code is going to:

  1. Consummate addMinuteAct function we added during setup, and as a consequence, the balance of the application.
  2. Create a MindfulSession of 1 infinitesimal starting now
  3. Save this new MindfulSession to the HealthKit
  4. Update the label to reflect the new total Mindful Minute count

Start it upwardly!

With all that finished and the lawmaking written, you should be able to kickoff this app in your simulator, have the request to read and write from your HealthKit, and brainstorm viewing how often you've Meditated in the final 24 hours!

1*Z3YJ4P_pI3gt7v7ozZJuCg
Amazing!

Wrap up

At the beginning of this project, I was very excited to jump into HealthKit. I do run into it being positioned to modify the mode we and others collaborate with sensitive personal information.

Notwithstanding, I call up that Apple tree, in dissimilarity to other platforms, makes their API's a little too hard to observe both through their documentation and through XCode. Hopefully they volition improve this experience, merely until they practise, learning how to utilise HealthKit can be an practice in pulling teeth.

I hope this post saves you from having to stumble around and tin can get yous aircraft your products faster!

?‍ This is open source! you tin find it here on Github
❤️ I simply write about programming and remote work. If yous follow me on Twitter I won't waste product your time.

Learn to lawmaking for free. freeCodeCamp's open source curriculum has helped more than xl,000 people get jobs as developers. Go started

lewiswarts1960.blogspot.com

Source: https://www.freecodecamp.org/news/read-write-mindful-minutes-from-healthkit-with-swift-232b65118fe2/

0 Response to "Read and Write Info in a Swift App"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel