为什么我的iPhone无法从Apple Watch获得heartRate数据,但手表扩展可以吗?(Why can't my iPhone get heartRate data from an

编程入门 行业动态 更新时间:2024-10-23 23:25:20
为什么我的iPhone无法从Apple Watch获得heartRate数据,但手表扩展可以吗?(Why can't my iPhone get heartRate data from an Apple Watch, but the watch extension can?)

我可以通过watchkit app扩展中的workoutSession和HKAnchoredObjectQuery获取数据。 我也想获得heartRate并在我的iPhone上显示数据。 所以我使用HKSampleQuery来获取模拟器(手表和iPhone),但是当我使用iPhone并观看测试时。 我的iPhone只能获得一次heartRate。

//码

override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. guard let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return } // 1. Build the Predicate let past = NSDate.distantPast() as NSDate let now = NSDate() let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None) // 2. Build the sort descriptor to return the samples in descending order let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false) // 3. we want to limit the number of samples returned by the query to just 1 (the most recent) // 4. Build samples query let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor]) { (sampleQuery, HKSample, error ) -> Void in // Get the samples guard let heartRateSamples = HKSample as? [HKQuantitySample] else {return} if(heartRateSamples.count > 0){ let count : Double = Double(heartRateSamples.count) var sum = 0.0; for quantitySample in heartRateSamples { let value = quantitySample.quantity.doubleValueForUnit(self.heartRateUnit); sum += value; } let avg = sum/count; self.HeartRateSum.text = String(sum) self.Count.text = String(count) self.SilentHeartRate.text = String(avg) } } // 5. Execute the Query self.healthStore.executeQuery(sampleQuery) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { sleep(15) while(true){ self.getRecentHeartRate() } }); } func getRecentHeartRate() ->Void{ guard let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return } let past = NSDate.distantPast() as NSDate let now = NSDate() let limit = 1 let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None) // 2. Build the sort descriptor to return the samples in descending order let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false) let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor]) { (sampleQuery, HKSample, error ) -> Void in // Get the samples guard let heartRateSample = HKSample as? [HKQuantitySample] else {return} guard let recentHeartRate = heartRateSample.first else{return} let value = recentHeartRate.quantity.doubleValueForUnit(self.heartRateUnit) dispatch_async(dispatch_get_main_queue()) { self.heartRate.text = String(UInt16(value)) } } self.healthStore.executeQuery(sampleQuery) }

I could get the data by workoutSession and HKAnchoredObjectQuery in watchkit app extension. And I also want to get heartRate and display the data on my iPhone. So I use HKSampleQuery to get by Simulator(watch and iPhone).But when I use the iPhone and watch to test. My iPhone could get the heartRate only once.

//code

override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. guard let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return } // 1. Build the Predicate let past = NSDate.distantPast() as NSDate let now = NSDate() let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None) // 2. Build the sort descriptor to return the samples in descending order let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false) // 3. we want to limit the number of samples returned by the query to just 1 (the most recent) // 4. Build samples query let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor]) { (sampleQuery, HKSample, error ) -> Void in // Get the samples guard let heartRateSamples = HKSample as? [HKQuantitySample] else {return} if(heartRateSamples.count > 0){ let count : Double = Double(heartRateSamples.count) var sum = 0.0; for quantitySample in heartRateSamples { let value = quantitySample.quantity.doubleValueForUnit(self.heartRateUnit); sum += value; } let avg = sum/count; self.HeartRateSum.text = String(sum) self.Count.text = String(count) self.SilentHeartRate.text = String(avg) } } // 5. Execute the Query self.healthStore.executeQuery(sampleQuery) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { sleep(15) while(true){ self.getRecentHeartRate() } }); } func getRecentHeartRate() ->Void{ guard let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return } let past = NSDate.distantPast() as NSDate let now = NSDate() let limit = 1 let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None) // 2. Build the sort descriptor to return the samples in descending order let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false) let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor]) { (sampleQuery, HKSample, error ) -> Void in // Get the samples guard let heartRateSample = HKSample as? [HKQuantitySample] else {return} guard let recentHeartRate = heartRateSample.first else{return} let value = recentHeartRate.quantity.doubleValueForUnit(self.heartRateUnit) dispatch_async(dispatch_get_main_queue()) { self.heartRate.text = String(UInt16(value)) } } self.healthStore.executeQuery(sampleQuery) }

最满意答案

你可以尝试这个获得heartRate

func readHeartRate() { let nowDate = NSDate() let calendar = NSCalendar.autoupdatingCurrentCalendar() let yearMonthDay: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day] let components: NSDateComponents = calendar.components(yearMonthDay , fromDate: nowDate) let beginOfDay: NSDate = calendar.dateFromComponents(components)! readHRbyDate(HKObjectQueryNoLimit, startDate: beginOfDay, endDate: nowDate) { (hrData, error) in print("heart Rate") // print(hrData) } } func readHRbyDate(latestXSamples: Int, startDate: NSDate, endDate: NSDate, completion: (((String, CGFloat), NSError!) -> Void)!) { let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.None) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true) var HRdata:(String,CGFloat) = ("N/A",0) var bpm: Int = 0 var totalBPMforDay = [Int]() var BPMCount: Int = 0 var sumBPM: Int = 0 let query = HKSampleQuery(sampleType: sampleType!, predicate: predicate, limit: latestXSamples, sortDescriptors: [sortDescriptor]) { (query, results, error) in if let queryError = error { print("Problem fetching HR data") completion(("nil",0.0),queryError) return }else{ for result in results! { bpm = Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0) totalBPMforDay += [Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0)] BPMCount = Int(totalBPMforDay.count) sumBPM += Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0) let HRAvg = sumBPM / BPMCount //HRdata = (self.getDayOfWeek(result.startDate),CGFloat(HRAvg)) let dateFormatter = MyAPIClient.sharedClient.apiClientDateFormatter() // create your date formatter HRdata = (dateFormatter.stringFromDate(result.startDate),CGFloat(HRAvg)) print(HRdata, bpm) } if completion != nil { completion(HRdata,nil) } } } executeQuery(query) }

You can try this for getting heartRate

func readHeartRate() { let nowDate = NSDate() let calendar = NSCalendar.autoupdatingCurrentCalendar() let yearMonthDay: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day] let components: NSDateComponents = calendar.components(yearMonthDay , fromDate: nowDate) let beginOfDay: NSDate = calendar.dateFromComponents(components)! readHRbyDate(HKObjectQueryNoLimit, startDate: beginOfDay, endDate: nowDate) { (hrData, error) in print("heart Rate") // print(hrData) } } func readHRbyDate(latestXSamples: Int, startDate: NSDate, endDate: NSDate, completion: (((String, CGFloat), NSError!) -> Void)!) { let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.None) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true) var HRdata:(String,CGFloat) = ("N/A",0) var bpm: Int = 0 var totalBPMforDay = [Int]() var BPMCount: Int = 0 var sumBPM: Int = 0 let query = HKSampleQuery(sampleType: sampleType!, predicate: predicate, limit: latestXSamples, sortDescriptors: [sortDescriptor]) { (query, results, error) in if let queryError = error { print("Problem fetching HR data") completion(("nil",0.0),queryError) return }else{ for result in results! { bpm = Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0) totalBPMforDay += [Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0)] BPMCount = Int(totalBPMforDay.count) sumBPM += Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0) let HRAvg = sumBPM / BPMCount //HRdata = (self.getDayOfWeek(result.startDate),CGFloat(HRAvg)) let dateFormatter = MyAPIClient.sharedClient.apiClientDateFormatter() // create your date formatter HRdata = (dateFormatter.stringFromDate(result.startDate),CGFloat(HRAvg)) print(HRdata, bpm) } if completion != nil { completion(HRdata,nil) } } } executeQuery(query) }

更多推荐

本文发布于:2023-08-03 13:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391362.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:手表   数据   Watch   iPhone   Apple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!