ios healthkit_如何使用Swift从iOS的HealthKit中读写Mindful Minutes

ios healthkit

by Ben Church

通过本教堂

如何使用Swift从iOS的HealthKit中读写Mindful Minutes (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 so you don’t have to!

我花了一些时间弄清楚如何从HealthKit进行读写,因此您不必这样做!

I absolutely love the route Apple has been going with their iOS SDK’s. (Their hardware not so much). Apple’s focus on security has allowed it 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’s sensitive personal info.

我绝对喜欢Apple使用其iOS SDK的路线。 ( 他们的硬件没那么多 )。 苹果公司对安全性关注使它成为一家可以信任您的敏感信息的可靠公司。 这使iPhone成为最适合托管医疗数据的设备。 因此,它们也是制作与用户的敏感个人信息对接的软件的最佳设备。

With this in mind, I believe it’s essential to know how to read and write from Apple’s HealthKit so that we as 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’s HealthKit.

考虑到这一点,我相信了解如何从Apple的HealthKit进行读写非常重要,以便我们作为开发人员能够利用Apple本身的地位。因此,今天的教程将着重于阅读和编写Apple的HealthKit的Mindful Minutes

By the end of this tutorial, you will have learned how to:

在本教程结束时,您将学习如何:

  • Setup a basic iOS app

    设置基本的iOS应用
  • Request permission to read and write data from HealthKit

    请求从HealthKit读取和写入数据的权限
  • Read and query data from HealthKit

    从HealthKit读取和查询数据
  • Write data back to HealthKit

    将数据写回到HealthKit

Alright let’s jump into setting up the XCode Project. ?

好吧,让我们进入建立XCode项目的过程。 ?

设置骨架 (Setup the Skeleton)

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

每个出色的项目都从同一屏幕开始(如果您只是在寻找代码,则可以跳过此部分)。

1.创建一个新项目 (1. Create a new project)

Let’s kick this off by creating a new Single View App project in XCode.

让我们从XCode创建一个新的Single View App项目开始。

2.包括HealthKit (2. Include HealthKit)

Once we’ve created the project, we need to bundle HealthKit with our application:

创建项目后,我们需要将HealthKit与我们的应用程序捆绑HealthKit

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

并更新info.plist文件,以包含当我们要求其访问数据的权限时用户将看到的内容。

Add the following xml to the info.plist file:

将以下xml添加到info.plist文件中:

3.创建一个基本的UI (3. Create a basic UI)

To finish up the setup, we will want to create a simple UI that will allow us to view the data we have read from the HealthKit and provide an action that will allow us to trigger a write back to the HealthKit.

为了完成设置,我们将要创建一个简单的UI,该UI将允许我们查看从HealthKit读取的数据,并提供一项操作,使我们能够触发对HealthKit的写回。

Start by opening the storyboard and:

首先打开storyboard然后:

  1. Add a label and connect it to the ViewController.swift file under the name mindfulMinuteLabel

    添加标签并将其连接到名称为mindfulMinuteLabelViewController.swift文件。

  2. Add a button and connect it to an Action in the ViewController.swift file titled addMinuteAct

    添加一个按钮,并将其连接到一个ActionViewController.swift名为文件addMinuteAct

呼吸一些生命…… (Breath some life into it…)

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

现在我们已经建立了基础架构,是时候编写将与我们一直在谈论的HealthKit进行所有接口的逻辑了。

1.寻求许可 (1. Ask for permission)

Every HealthKit app needs to explicitly ask for a user’s permission for every type of read and write it needs to do. To accomplish this, we want to ask on viewDidLoad for permission to read Mindful Sessions and for permission to write Mindful Sessions.

每个HealthKit应用程序都需要针对其需要执行的每种类型的读写操作明确请求用户的许可。 为此,我们想在viewDidLoad上请求读取Mindful Session的权限和写入Mindful Session的权限。

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

现在,当应用程序运行时,下面的屏幕将提示您。

If you are running this right now, you will want to comment out self.retrieveMindfulMinutes()

如果您现在正在运行此功能,则将要注释掉self.retrieveMindfulMinutes()

2.阅读正念的纪要 (2. Reading Mindful Minutes)

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

到目前为止,这非常简单:创建UI,征求许可。 接下来,我们将阅读HealthKit的内容。 尽管Apple为我们提供了功能强大的UI,但它不一定直观。 因此,我将向您展示代码,然后再对其进行解释。

The query we execute to retrieve our Mindful Sessions can be broken into four components:

我们执行的检索我们的Mindful Session的查询可以分为四个部分:

1. Sort by End Date

1.按结束日期排序

The first section of this code is optional but useful to know. What we are doing is asking the query to give us the list of Mindful Sessions ordered by their end time with the most recent session being first.

该代码的第一部分是可选的,但很有用。 我们正在做的是让查询提供给我们Mindful Sessions列表,这些列表按其结束时间排序,最近的会话排在第一位。

2. Use the Predicate to define the Query

2.使用谓词定义查询

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

我们代码的下一部分处理“查询”的实际细节:我们正在寻找什么数据子集。 在我们的情况下,我们需要过去24小时内的所有样本。

3. Compose and Run your Query

3.编写并运行查询

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

最后,我们希望将sampleType想要的sortDescriptorpredicate和sampleType与处理查询返回的结果的函数( resultsHandler )结合起来。 将其全部组成一个HKSampleQuery ,剩下的唯一步骤就是执行它!

4. Aggregating the session data and updating the UI

4.聚合会话数据并更新UI

Inside the function we defined as our resultsHandler in the previous section, we want to:

在上一节中定义为resultsHandler的函数中,我们想要:

  1. Get the total time for each Mindful Session

    获取每次正念会话的总时间
  2. Sum all total times to get the total number of Mindful minutes over the last 24 hours.

    对所有总时间求和,以获取过去24小时内的Mindful分钟总数。
  3. Update our label with the total.

    用总数更新我们的标签。

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

如果您了解map和reduce的概念,那么所有这些都应该相对简单。 如果您不熟悉这些,我建议您花些时间学习它们。 在大多数编程语言中都可以找到它们,并且很好地介绍了函数式编程的美好世界。

The only piece that may not be straightforward is why we wrap

唯一可能不简单的部分是我们包装的原因

self.meditationMinutesLabel.text = labelText

in DispatchQueue.main.async . The reason we do this is so we can update the UI without blocking the main thread of the application. This is a convention enforced by the compiler itself!

DispatchQueue.main.async 。 这样做的原因是,我们可以更新UI而不阻塞应用程序的主线程。 这是由编译器本身强制执行的约定!

写入数据 (Writing the data)

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

在上面,我们讨论了如何从HealthKit读取信息。 但是我们如何向其中写入数据? 值得庆幸的是,此过程非常简单。 以下代码将转到:

  1. Complete addMinuteAct function we added during setup, and as a result, the rest of the application.

    完整的addMinuteAct函数,是我们在安装过程中添加的,因此是应用程序的其余部分。

  2. Create a MindfulSession of 1 minute starting now

    从现在开始创建1分钟的MindfulSession

  3. Save this new MindfulSession to the HealthKit

    将此新的MindfulSession保存到HealthKit

  4. Update the label to reflect the new total Mindful Minute count

    更新标签以反映新的Mindful Minute总数

开始吧! (Start it up!)

With all that finished and the code written, you should be able to start this app in your simulator, accept the request to read and write from your HealthKit, and begin viewing how often you’ve Meditated in the last 24 hours!

完成所有步骤并编写代码后,您应该能够在模拟器中启动该应用程序,接受从HealthKit进行读写的请求,并开始查看最近24小时内您进行冥想的频率!

结语 (Wrap up)

At the beginning of this project, I was very excited to jump into HealthKit. I do see it being positioned to change the way we and others interact with sensitive personal information.

在这个项目的开始,我很高兴能进入HealthKit。 我确实看到它可以改变我们和其他人与敏感个人信息互动的方式。

However, I think that Apple, in contrast to other platforms, makes their API’s a little too hard to discover both through their documentation and through XCode. Hopefully they will improve this experience, but until they do, learning how to use HealthKit can be an exercise in pulling teeth.

但是,我认为与其他平台相比,Apple使得通过其文档和XCode都难以发现其API。 希望他们会改善这种体验,但是直到他们这样做之前,学习如何使用HealthKit可以成为拔牙的练习。

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

我希望这篇文章可以使您免于绊倒,并且可以让您更快地发货!

?‍ This is open source! you can find it here on Github

?这是开源的! 您可以在Github上找到它

❤️ I only write about programming and remote work. If you follow me on Twitter I won’t waste your time.

❤️我只写关于编程和远程工作的文章。 如果您在Twitter上关注我,我不会浪费您的时间。

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

ios healthkit

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值