Swift IOS healthkit use case: get the body temperature list hkhealthstore


Swift IOS healthkit use case: get the body temperature list hkhealthstore


It seems that there is little aboutswiftThe courses and articles are basicallyObjectCYes, so send it.

To learnSwiftYou can go to Stanford University’s course, click here, of course, English is good, after reading will be. That’s what I learned from this tutorial.
In addition, installation is recommendedDashThis application is a reference API tool softwareSwiftEssential for development

Development environment of this tutorial:

  • XCode 11.3.1
  • iOS 13+

Make an application to obtain body temperature data in health application

The results are as follows:

Swift IOS healthkit use case: get the body temperature list hkhealthstore

Description of all entity classes of healthkit

The following picture:
There are mainly

  1. Data storage object:HKObject HKSampleThese two are abstract classes. When you use them, you need to use their actual body classes, as shown in the following figure
  2. Data query object:HKQueryUsed to set up various query examples,
  3. Data unit object:HKUnitUnits that can represent all health data, such as:riceMileCalorieCentigradeWait

Swift IOS healthkit use case: get the body temperature list hkhealthstore

Process description of data query

  1. stayInfo.plistTwo values are added to the file, and the following text description will be displayed in the application request authorization window

    1. This is the name in normal modeSwift IOS healthkit use case: get the body temperature list hkhealthstore
    2. Right click selectionRaw Key & Valuesthis muchSwift IOS healthkit use case: get the body temperature list hkhealthstore
  2. When operating health data, first determine whether health data is supportedisHealthDataAvailable() -> Bool
  3. App needs to go firstHealthyThe application obtains the authorization of the data type you want to operate, and the health data can be processed only after the user agreesrequestAuthorization(toShare:, read:, completion: (Bool, Error?) -> Void)
  4. Then you need to create a query object using theHKQueryThe following classes of this abstract class are described in the figure above. HereHKSampleQuery(sample query) for example, different query types have different corresponding parameters

    1. When creating, you need to enter the corresponding parameters
    2. Data type and data ID you want to querysampleTypeThe type of sample to query, and the specific type of data: for example, body temperature
    3. Time condition of querypredicate, this is the predicate of time. If left blank, time will not be filtered
    4. Number of querieslimit
    5. Sorting method of query resultssortDescriptors
    6. Finally, the callback method(query, results, error) queryIs the current query object,results?Is the result of the query,error?Is the error message when an error occurs,The main operation is here

Look at code


//  TemperatureTableViewController.swift
//  BodyTemparature
//  Created by Kyle on 2020/2/10.
//  Copyright © 2020 Cyan Maple. All rights reserved.

import UIKit
import HealthKit

///Get body temperature data in health
class TemperatureTableViewController: UITableViewController {
    //Store the queried data
    private var temperatureSamples: Array<HKSample> = []
    private var kit: HKHealthStore! {
        return HKHealthStore()
    private let queryType = HKQuantityType.quantityType(forIdentifier: .bodyTemperature)!
    private let querySample = HKSampleType.quantityType(forIdentifier: .bodyTemperature)!
    override func viewDidLoad() {
        Navigationitem.title = "body temperature record top 10"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add",
                                                            style: .plain,
                                                            target: self,
                                                            action: #selector(buttonPressed))
        //If IOS 11 + displays a headline
        if #available(iOS 11.0, *) {
            self.navigationController?.navigationBar.prefersLargeTitles = true
        if HKHealthStore.isHealthDataAvailable(){
            //  Write Authorize
            let queryTypeArray: Set<HKSampleType> = [queryType]
            //  Read Authorize
            let querySampleArray: Set<HKObjectType> = [querySample]
            kit.requestAuthorization(toShare: queryTypeArray, read: querySampleArray) { (success, error) in
                if success{
                } else {
                    self.showAlert(title: "Fail", message: "Unable to access to Health App", buttonTitle: "OK")
        } else {
            // show alert
            Showalert (Title: "fail", message: "device does not support health", buttontitle: "exit")
    @objc func buttonPressed() {
        print("Button Pressed")
        // TODO: Add temperature in modal view
    func getTemperatureData(){
        //Time query criteria object
        let calendar = Calendar.current
        let todayStart =  calendar.date(from: calendar.dateComponents([.year,.month,.day], from: Date()))
        let dayPredicate = HKQuery.predicateForSamples(withStart: todayStart,
                                                       end: Date(timeInterval: 24*60*60,since: todayStart!),
                                                       options: HKQueryOptions.strictStartDate) */

        //Create query object
        Let temperaturesamplequery = hksamplequery (sampletype: querysample, // type object to get
                                                   Predict: Nil, // time parameter. If it is empty, time is not limited
                                                   Limit: 10, // get quantity
                                                   Sortdescriptors: [nssortdescriptor (key: hksamplesortidentifierstartdate, ascending: false)]) // the sort method of the acquired data
        { (query, results, error) in
            ///After getting the result, the results are returned [hksample]?
            if let samples = results {
                //Insert into tableview one by one
                for sample in samples {
                    DispatchQueue.main.async {
                        self.tableView.insertRows(at: [IndexPath(row: self.temperatureSamples.firstIndex(of: sample)!, section:0)],
                                                  with: .right   )

        //Perform query operation
    ///Custom method: input hksample output date and temperature
    func getTemperatureAndDate(sample: HKSample) -> (Date, Double) {
        let quantitySample = sample as! HKQuantitySample
        let date = sample.startDate
        let temperature = quantitySample.quantity.doubleValue(for: .degreeCelsius())
        return (date, temperature)
    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return temperatureSamples.count
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TemperatureCell", for: indexPath)
        let (date, temperature) = getTemperatureAndDate(sample: temperatureSamples[indexPath.row])
        cell.textLabel?.text = String(temperature)
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .short
        dateFormatter.locale = Locale(identifier: "zh_CN")
        cell.detailTextLabel?.text = dateFormatter.string(from: date)
        return cell
    // MARK: - Tool Methods - Alert
    func showAlert(title: String, message: String, buttonTitle: String) {
        let alert = UIAlertController(title: title,
                                      message: message,
                                      preferredStyle: .alert)
        let okAction = UIAlertAction(title: buttonTitle, style: .default, handler: { (action) in
        DispatchQueue.main.async {
            self.present(alert, animated: true, completion: nil)

Recommended Today

Interviewer: young man, what do you think of the principle of distributed system

1 Concept 1.1 model 1.2 copies 1.3 indicators for measuring distributed systems 2. Principle of distributed system 2.1 data distribution 2.2 basic copy agreement 2.3 lease mechanism 2.4 quorum mechanism 2.5 log technology 2.6 two phase submission protocol 2.7 MVCC 2.8 Paxos protocol 2.9 CAP 1 Concept 1.1 model node In a specific project, a […]