如何使用 Swift 从 iOS HealthKit 应用程序读取心率?

2024-03-05

我正在使用以下 Swift 代码。

let sampleType : HKSampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
let nowDate: NSDate = NSDate()
var calendar: NSCalendar = NSCalendar.autoupdatingCurrentCalendar()

let yearMonthDay: NSCalendarUnit = NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit

var components: NSDateComponents = calendar.components(yearMonthDay , fromDate: nowDate)
var beginOfDay : NSDate = calendar.dateFromComponents(components)!
var predicate : NSPredicate = HKQuery.predicateForSamplesWithStartDate(beginOfDay, endDate: nowDate, options: HKQueryOptions.StrictStartDate)

let squery: HKStatisticsQuery = HKStatisticsQuery(quantityType: sampleType, quantitySamplePredicate: predicate, options: HKStatisticsOptions.None) { (qurt, resul, errval) -> Void in

    dispatch_async( dispatch_get_main_queue(), { () -> Void in
        var quantity : HKQuantity = result.averageQuantity;
        var beats : double = quantity.doubleValueForUnit(HKUnit.heartBeatsPerMinuteUnit())
        // [quantity doubleValueForUnit:[HKUnit heartBeatsPerMinuteUnit]];
         self.txtfldHeartRate.text = "\(beats)"
    })

}

healthManager.healthKitStore.executeQuery(squery)

我收到以下错误消息:

找不到类型“HKStatisticsQuery”的初始值设定项,该初始值设定项接受类型“(quantityType: HKSampleType, amountSamplePredicate: NSPredicate, options: HKStatisticsOptions, (_, _, _) -> Void)”类型的参数列表

请告诉我如何解决这个问题。


从 ViewController 读取数据(不是 Apple Watch 扩展)

Swift 5

let health: HKHealthStore = HKHealthStore()
let heartRateUnit:HKUnit = HKUnit(from: "count/min")
let heartRateType:HKQuantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
    var heartRateQuery:HKSampleQuery?

/*Method to get todays heart rate - this only reads data from health kit. */
 func getTodaysHeartRates() {
    //predicate
    let calendar = NSCalendar.current
    let now = NSDate()
    let components = calendar.dateComponents([.year, .month, .day], from: now as Date)
    
    guard let startDate:NSDate = calendar.date(from: components) as NSDate? else { return }
    var dayComponent    = DateComponents()
    dayComponent.day    = 1
    let endDate:NSDate? = calendar.date(byAdding: dayComponent, to: startDate as Date) as NSDate?
    let predicate = HKQuery.predicateForSamples(withStart: startDate as Date, end: endDate as Date?, options: [])

    //descriptor
    let sortDescriptors = [
                            NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
                          ]
    
    heartRateQuery = HKSampleQuery(sampleType: heartRateType, predicate: predicate, limit: 25, sortDescriptors: sortDescriptors, resultsHandler: { (query, results, error) in
        guard error == nil else { print("error"); return }

        self.printHeartRateInfo(results: results)
    }) //eo-query
    
    health.execute(heartRateQuery!)
 }//eom

/*used only for testing, prints heart rate info */
private func printHeartRateInfo(results:[HKSample]?)
{
    for (_, sample) in results!.enumerated() {
        guard let currData:HKQuantitySample = sample as? HKQuantitySample else { return }

        print("[\(sample)]")
        print("Heart Rate: \(currData.quantity.doubleValue(for: heartRateUnit))")
        print("quantityType: \(currData.quantityType)")
        print("Start Date: \(currData.startDate)")
        print("End Date: \(currData.endDate)")
        print("Metadata: \(currData.metadata)")
        print("UUID: \(currData.uuid)")
        print("Source: \(currData.sourceRevision)")
        print("Device: \(currData.device)")
        print("---------------------------------\n")
    }//eofl
}//eom

Swift 3

let health: HKHealthStore = HKHealthStore()
let heartRateUnit:HKUnit = HKUnit(fromString: "count/min")
let heartRateType:HKQuantityType   = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
var heartRateQuery:HKSampleQuery?


/*Method to get todays heart rate - this only reads data from health kit. */
 func getTodaysHeartRates()
    {
        //predicate
        let calendar = NSCalendar.currentCalendar()
        let now = NSDate()
        let components = calendar.components([.Year,.Month,.Day], fromDate: now)
        guard let startDate:NSDate = calendar.dateFromComponents(components) else { return }
        let endDate:NSDate? = calendar.dateByAddingUnit(.Day, value: 1, toDate: startDate, options: [])
        let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)
        
        //descriptor
        let sortDescriptors = [
                                NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
                              ]
        
        heartRateQuery = HKSampleQuery(sampleType: heartRateType,
                                        predicate: predicate,
                                        limit: 25,
                                        sortDescriptors: sortDescriptors)
            { (query:HKSampleQuery, results:[HKSample]?, error:NSError?) -> Void in
                
                guard error == nil else { print("error"); return }

                //self.printHeartRateInfo(results)
                
                self.updateHistoryTableViewContent(results)

        }//eo-query
        health.executeQuery(heartRateQuery!)
        
   }//eom

/*used only for testing, prints heart rate info */
private func printHeartRateInfo(results:[HKSample]?)
    {
        for(var iter = 0 ; iter < results!.count; iter++)
        {
            guard let currData:HKQuantitySample = results![iter] as? HKQuantitySample else { return }
            
            print("[\(iter)]")
            print("Heart Rate: \(currData.quantity.doubleValueForUnit(heartRateUnit))")
            print("quantityType: \(currData.quantityType)")
            print("Start Date: \(currData.startDate)")
            print("End Date: \(currData.endDate)")
            print("Metadata: \(currData.metadata)")
            print("UUID: \(currData.UUID)")
            print("Source: \(currData.sourceRevision)")
            print("Device: \(currData.device)")
            print("---------------------------------\n")
        }//eofl
    }//eom

使用Apple Watch扩展读取数据:

要在 Apple Watch 中执行查询,请执行以下操作:

        heartRateQuery = self.createStreamingQuery()
        health.executeQuery(heartRateQuery!)

不要忘记属性:

let health: HKHealthStore = HKHealthStore()
let heartRateUnit:HKUnit = HKUnit(fromString: "count/min")
let heartRateType:HKQuantityType   = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
var heartRateQuery:HKQuery?

/*以下方法没有限制,一旦执行查询就无限查询heart */

private func createStreamingQuery() -> HKQuery
    {
        let queryPredicate  = HKQuery.predicateForSamplesWithStartDate(NSDate(), endDate: nil, options: .None)
        
    let query:HKAnchoredObjectQuery = HKAnchoredObjectQuery(type: self.heartRateType, predicate: queryPredicate, anchor: nil, limit: Int(HKObjectQueryNoLimit))
    { (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in
    
        if let errorFound:NSError = error
        {
            print("query error: \(errorFound.localizedDescription)")
        }
        else
        {
            //printing heart rate
             if let samples = samples as? [HKQuantitySample]
              {
                 if let quantity = samples.last?.quantity
                 {
                     print("\(quantity.doubleValueForUnit(heartRateUnit))")
                 }
               }
        }
    }//eo-query
    
    query.updateHandler =
        { (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in
            
            if let errorFound:NSError = error
            {
                print("query-handler error : \(errorFound.localizedDescription)")
            }
            else
            {
                  //printing heart rate
                  if let samples = samples as? [HKQuantitySample]
                  {
                       if let quantity = samples.last?.quantity
                       {
                          print("\(quantity.doubleValueForUnit(heartRateUnit))")
                       }
                  }
            }//eo-non_error
    }//eo-query-handler
    
    return query
}//eom

如何请求授权?

func requestAuthorization()
    {
    //reading
    let readingTypes:Set = Set( [heartRateType] )
    
    //writing
    let writingTypes:Set = Set( [heartRateType] )
    
    //auth request
    health.requestAuthorizationToShareTypes(writingTypes, readTypes: readingTypes) { (success, error) -> Void in
        
        if error != nil
        {
            print("error \(error?.localizedDescription)")
        }
        else if success
        {
            
        }
    }//eo-request
}//eom
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Swift 从 iOS HealthKit 应用程序读取心率? 的相关文章

  • NSUserDefaults 多久同步一次?

    的文档NSUserDefaults说synchronise方法被定期调用 但没有提及频率 10分钟的谷歌搜索没有发现任何信息 发生的频率是多少synchronise方法调用 这是一个未公开的实现细节 可能甚至不是一个恒定的时间间隔 但是 您
  • 如何在 Firebase Analytics 事件中报告参数

    我用过Fabric with iOS在此之前 在同一分析事件中报告自定义参数非常容易 如下所示 Answers logCustomEvent withName saved border customAttributes image inde
  • 从 IOS 应用程序注销的完美方法是什么?

    下面的代码可以工作 但有一个错误 场景是 我首先登录进入应用程序系统 登录成功后 应用程序将设置 UserDefaults UserId 之后 我可以使用存储的 UserId 导航应用程序视图 一旦我进入设置和选项卡注销 这将清除 User
  • ReactNative - 未处理的 JS 异常:SyntaxError

    当我尝试在 iOS 8 上启动 RUN 应用程序时 出现这个奇怪的错误 Unhandled JS Exception SyntaxError仅此而已 不再有更多信息 有any1偶然发现这个问题吗 在 iOs 9 上应用程序运行正常 x代码版
  • 在 Xcode5 中使用 XCTest 时 AFNetworking 导致错误

    我正在使用 Xcode 5 现在刚刚开始对现有项目进行单元测试 为此我添加了CocoaTouch Unit Testing Bundle作为我的项目的目标 目标名称是 MyAppTests 我之前使用添加了 AFNetworking 库Co
  • Xcode 错误 - 架构 x86_64 的未定义符号?

    我正在运行 Swift 4 和 Xcode 9 beta 我收到此错误 但我不知道如何解决它 我什至不知道这是什么意思 Undefined symbols for architecture x86 64 T0So22AVCapturePho
  • HTML 分页

    有没有html分页的开源项目 我正在为 iPhone 开发一个应用程序 我想在 UIWebView 上显示 HTML 文件 并且不希望用户向下滚动以查看屏幕上未显示的剩余内容 我想在第二个 UIWebView 上显示剩余的内容 我怎样才能做
  • UITableView 快速获取 titleForHeadersInSection

    我想在 UITableView 的部分中设置标题的标题 语法是什么swift设置该部分中标题的标题 func tableView tableView UITableView titleForHeaderInSection section I
  • 为什么 UITableViewCell 不可访问(对于 VoiceOver)

    我并不是想解决任何问题 当然你可以设置isAccessibilityEnabled true它有效 我的问题是 为什么它默认关闭并且界面生成器中没有适当的部分 在我看来 不建议使 UITableViewCell 子类可访问 有没有更好的方法
  • iOS UITableViewCell cell.imageView 设置圆角

    嘿我正在尝试设置cell imageView s cornerRadius 但似乎不起作用 cell imageView layer cornerRadius 9 它会起作用还是我应该添加自定义UIImageView在我的牢房里有圆角吗 我
  • 为 iOS 应用程序加载基于 SVG 的图像资源

    我从 thenounproject 购买了一个图标作为 SVG 图像 然后我使用一个名为的 macOS 程序Gapplin http gapplin wolfrosch com 将此 SVG 导出为 PNG 图像 它显示为 100x100
  • 以弯曲格式显示文本

    我正在寻找以曲线格式绘制一些文本 我使用哪个控件并不重要 UITextField UILabel or UITextView 我只想显示如图所示的文本 仍在寻找解决方案 请帮忙 查看此链接 https nodeload github com
  • 以编程方式从底部裁剪图像

    我正在开发自定义相机应用程序 一切进展顺利 但我在从底部裁剪图像时遇到了问题 即 裁剪后的图像与原始图像具有完全相同的宽度 但高度将为原始图像的 1 3 并且必须从底部开始 斯威夫特3解决方案 func cropBottomImage im
  • 在 swift 中将简单字符串转换为 JSON 字符串

    我知道有一个同标题的问题here https stackoverflow com questions 30825755 convert string to json string in swift 但在那个问题中 他试图将字典转换为 JSO
  • iOS 解决方法:在没有 CSS 属性的情况下平滑滚动 滚动行为:平滑?

    编辑 我找到了一个 jQuery 解决方案 https codepen io chriscoyier pen dpBMVP https codepen io chriscoyier pen dpBMVP这个确实可以在 iOS 上运行 我想
  • ios 在后台处理推送通知

    我想保存应用程序处于后台状态时到达的推送通知 我知道关于 void application UIApplication application didReceiveRemoteNotification NSDictionary userIn
  • XCode 4.5 给我“SenTestingKit/SenTestKit.h”文件未找到,但适用于 4.4.1

    我刚刚安装了 XCode 4 5 它在我现有的项目之一上给了我一个 SenTestingKit SenTestingKit h 文件未找到错误 此错误仅发生在 XCode 4 5 中 但它在 4 4 1 上编译正常 我已经检查过SenTes
  • NSCFData fastCharacterContents 崩溃? [关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我目前在控制台中收到此崩溃日志 20
  • iOS 视图控制器内存在被关闭后未释放

    当用户单击按钮时 它会显示一个带有两个视图控制器的新选项卡栏视图控制器 我是这样做的 ACLevelDownloadController dvc ACLevelDownloadController alloc initWithNibName
  • 设置/覆盖 UICollectionView 中单元格之间的填充

    我有一个 UICollectionView 但在获取单元格之间的填充时遇到了问题 理论上 我应该能够将屏幕除以 4 并且我可以获得包含 4 个图像的单元格大小 完美地占据屏幕宽度 但是 它选择不这样做 相反 它会创建 3 个具有巨大填充的图

随机推荐