J.Dhaik
J.Dhaik

Reputation: 103

Xamarin iOS Reading Step Counts from HealthKit

I am trying to read the stepcount from 365 days back in time from the user and then upload this to a server. But I'm currently stuck at extracting the data, I get the permission from the iOS healthkit correctly, but the return type of my data is just get "[0:] HealthKit.HKSample[]"

public void GetSteps()
{        
    var healthKitStore = new HKHealthStore();
    var stepRateType = HKQuantityType.Create(HKQuantityTypeIdentifier.StepCount);
    var sort = new NSSortDescriptor(HKSample.SortIdentifierStartDate, true);
    var q = new HKSampleQuery(stepRateType, HKQuery.GetPredicateForSamples(NSDate.Now.AddSeconds(TimeSpan.FromDays(-365).TotalSeconds), NSDate.Now.AddSeconds(TimeSpan.FromDays(1).TotalSeconds), HKQueryOptions.None), 0, new NSSortDescriptor[] { },
        new HKSampleQueryResultsHandler((HKSampleQuery query2,HKSample[] results, NSError error2) =>
        {
            var query = results; //property created within the model to expose later.
            Debug.WriteLine(query);
            Debug.WriteLine(results);
        }));
    healthKitStore.ExecuteQuery(q); 
}

Upvotes: 1

Views: 1152

Answers (1)

jskqmf
jskqmf

Reputation: 11

I think I know why you are getting "[0:] HealthKit.HKSample[]", you are trying to Debug.WriteLine an array of objects. The results variable is an array. Loop through the array instead and extract out the "Quantity", "StartDate", and "EndDate" among other fields that are available:

foreach (var item in results)
{
    var sample = (HKQuantitySample) item;
    var hkUnit = HKUnit.Count;
    var quantity = sample.Quantity.GetDoubleValue(hkUnit);
    var startDateTime = sample.StartDate.ToDateTime().ToLocalTime();
    var endDateTime = sample.EndDate.ToDateTime().ToLocalTime();
    Debug.WriteLine(quantity);
    Debug.WriteLine(startDateTime);
    Debug.WriteLine(endDateTime);
}

Upvotes: 1

Related Questions