2016-05-10 16 views
1

私は健康アプリケーションを作っています。私はSwiftのwalkingRunningDistanceHealthKitにしたいと思っています。しかし、私には問題があります。戻り値は0.0mileです。速攻でHealthKitを使用して歩行と走行距離を取得する方法

なぜ戻り値が0マイルですか?

私のコードはこれです。

func recentSteps3(completion: (Double, NSError?) ->()){ 
    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning) 

    let date = NSDate() 

    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! 

    let newDate = cal.startOfDayForDate(date) 

    let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: HKQueryOptions.StrictStartDate) 

    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { query, results, error in 

     var distance: Double = 0 

     if results?.count > 0 
     { 
      for result in results as! [HKQuantitySample] 
      { 
       distance += result.quantity.doubleValueForUnit(HKUnit.mileUnit()) 
      } 
     } 

     completion(distance, error) 
    } 

    healthAuth.healthStore.executeQuery(query) 
} 
+0

を数える取得するためにアクセスし、メソッドの下をrequstingための上記の方法あなたは、この問題を解決しました。私は同じ問題があります。 – muhammedkasva

答えて

0

あなたのコードは、ユーザーがアプリの許可を与えたHealthKit

  • から distanceWalkingRunningを読むために、ユーザからの許可を要求している

    1. 場合は値を返します。

    、あなたのコードは、承認を要求するには0

    を返しますされていない場合、あなたはtypesToRead私はHKStatisticsQueryを使用していることを信じて

    let distanceType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)! 
    

    かが含まれてい

    func requestAuthorization(toShare typesToShare: Set<HKSampleType>?, read typesToRead: Set<HKObjectType>?, completion: @escaping (Bool, Error?) -> Swift.Void) 
    

    を呼び出すことができますHKStatisticsCollectionQueryがより効率的になります。ここに例があります。

    guard let type = HKSampleType.quantityType(forIdentifier: .distanceWalkingRunning) else { 
        fatalError("Something went wrong retriebing quantity type distanceWalkingRunning") 
    } 
    let date = NSDate() as Date 
    let cal = Calendar(identifier: Calendar.Identifier.gregorian) 
    let newDate = cal.startOfDay(for: date) 
    
    let predicate = HKQuery.predicateForSamples(withStart: newDate as Date, end: NSDate() as Date, options: .strictStartDate) 
    
    let query = HKStatisticsQuery(quantityType: type, quantitySamplePredicate: predicate, options: [.cumulativeSum]) { (query, statistics, error) in   
        var value: Double = 0 
    
        if error != nil { 
         print("something went wrong") 
        } else if let quantity = statistics?.sumQuantity() { 
         value = quantity.doubleValue(for: HKUnit.mile()) 
        } 
        DispatchQueue.main.async { 
         completion(value) 
        } 
    } 
    healthStore.execute(query) 
    
  • 0
    healthStore =[HKHealthStore new]; 
    HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; 
    HKSampleType *sleepType = [HKSampleType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis]; 
    HKQuantityType *walkType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning]; 
    NSArray *arrayType = @[stepType,sleepType,walkType]; 
    
    [healthStore requestAuthorizationToShareTypes:[NSSet setWithArray:arrayType] 
                readTypes:[NSSet setWithArray:arrayType] completion:^(BOOL succeeded, NSError *error) { 
                 if (succeeded) { 
                  NSLog(@"Not working"); 
                  NSLog(@"error %@",error); 
                 } else { 
                  NSLog(@"Working!"); 
                  NSLog(@"error %@",error); 
                 } 
                 [self getStepCount]; 
                }]; 
    

    -(void)getStepCount{ 
        NSInteger limit = 0; 
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
        [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 
        NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:1372418789]; 
        // Divided by 1000 (i.e. removed three trailing zeros) ^^^^^^^^ 
        NSString *formattedDateString = [dateFormatter stringFromDate:startDate]; 
        // Fri, 28 Jun 2013 11:26:29 GMT 
        NSLog(@"start Date: %@", formattedDateString); 
        NSDateFormatter *dateFormatter1=[[NSDateFormatter alloc] init]; 
        [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
        NSLog(@"%@",[dateFormatter1 stringFromDate:[NSDate date]]); 
        NSString *dateString =[dateFormatter1 stringFromDate:[NSDate date]]; 
        NSDate *endDate = [dateFormatter1 dateFromString:dateString]; 
    
    
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictEndDate]; 
    
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning] 
             predicate: predicate 
             limit: limit 
             sortDescriptors: nil 
             resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error){ 
              dispatch_async(dispatch_get_main_queue(), ^{ 
               // sends the data using HTTP 
               int dailyAVG = 0; 
               NSLog(@"result : %@",results); 
               for(HKQuantitySample *samples in results) 
               { 
                NSLog(@"dailyAVG : %@",samples); 
               } 
               NSLog(@"dailyAVG : %d",dailyAVG); 
    
               NSLog(@"%@",@"Done"); 
              }); 
             }]; 
    [healthStore executeQuery:query]; 
    

    }

    +0

    客観的なcでそのうまく動作します。kindly https://objectivec2swift.com/#/converter/を使用して迅速に変換 –

    +1

    うわー〜ありがとう〜:) –

    関連する問題