2016-09-28 84 views
0

我可以通過workoutSession獲取數據,HKAnchoredObjectQuery可以在watchkit應用擴展程序中獲得。我也想獲得heartRate並在我的iPhone上顯示數據。所以我用模擬器(手錶和iPhone)使用HKSampleQuery。但是當我使用iPhone和手錶進行測試時。我的iPhone只能得到一次heartRate。爲什麼我的iPhone無法從Apple Watch獲得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) 
} 

回答

0

你可以嘗試這樣來心率

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) 
} 
+0

非常感謝。我想更新最近的心臟以在iPhone上顯示。收集heartRate的統計數據是穩定的。但我不知道爲什麼程序在模擬器上運行良好,但Iphone。 – Maxwell

+0

你有沒有試過這段代碼? –

+0

當然。當我進入該程序時,我可以聽到一次hearRate。我想更新用戶的heartRate並在程序運行時顯示數據。現在我測試我的代碼,每次獲取數據後都會睡(1)。它現在工作。但它仍然不穩定。我認爲原因是我的代碼太糟糕了。有內存泄漏或其他問題。 – Maxwell

相關問題