public static Task <double> ReadCurrentHeightInMetres(HKHealthStore store)
        {
            var tcs = new TaskCompletionSource <double>();

            var heightType = HKQuantityTypeIdentifierKey.Height;
            var heightUnit = HKUnit.Meter;
            var sort       = new NSSortDescriptor(HKSample.SortIdentifierStartDate, false);

            var sampleType = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.Height);

            var query = new HKSampleQuery(sampleType, null, 1, new NSSortDescriptor[] { sort },
                                          (q, data, error) =>
            {
                if (error == null)
                {
                    var amount = (data[0] as HKQuantitySample).Quantity.GetDoubleValue(heightUnit);
                    tcs.TrySetResult(amount);
                }
                else
                {
                    tcs.TrySetException(new NSErrorException(error));
                }
            });

            store.ExecuteQuery(query);

            return(tcs.Task);
        }
示例#2
0
		public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
		{
			HealthStore = new HKHealthStore ();
			SetupHealthStoreForTabBarControllers ();

			return true;
		}
示例#3
0
        public WorkoutDelegate(HKHealthStore healthStore, HKWorkoutSession workoutSession)
        {
            // Initialize
            this.HealthStore    = healthStore;
            this.WorkoutSession = workoutSession;

            // Attach this delegate to the session
            workoutSession.Delegate = this;
        }
示例#4
0
        public static async Task <IEnumerable <Workout> > GetWorkouts(HKHealthStore store, DateInterval dates)
        {
            var workoutType = HKObjectType.GetWorkoutType();

            var workouts = await RunQuery(store, workoutType, dates, sample => WorkoutParser.ParseWorkout((HKWorkout)sample));

            return(workouts.Match(
                       Some: w => w,
                       None: Enumerable.Empty <Workout>()));
        }
示例#5
0
 public HealthService()
 {
     if (HKHealthStore.IsHealthDataAvailable)
     {
         HealthStore = new HKHealthStore();
     }
     else
     {
         Debug.WriteLine("HEALTHKIT is not available on this device!");
     }
 }
        public static Task <(bool Result, NSError Error)> DeleteObjectsAsync(
            this HKHealthStore healthStore,
            HKObjectType objectType,
            NSPredicate predicate)
        {
            var tcs = new TaskCompletionSource <(bool, NSError)>();

            healthStore.DeleteObjects(
                objectType,
                predicate,
                (isCompleted, _, error) => tcs.SetResult((isCompleted, error)));

            return(tcs.Task);
        }
 public void GetHealthPermissionAsync(Action <bool> completion)
 {
     if (HKHealthStore.IsHealthDataAvailable)
     {
         HealthStore = new HKHealthStore();
         HealthStore.RequestAuthorizationToShare(DataTypesToWrite, DataTypesToRead, (bool authorized, NSError error) =>
         {
             completion(authorized);
         });
     }
     else
     {
         completion(false);
     }
 }
示例#8
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
                        #if DEVICETEST
            DeviceTest.Core.RegisteredTests.Instance.AddTest <HealthKitDeviceTest, HealthKitBasicDetails>();

            this.Window = new UIWindow();
            Window.RootViewController = new UINavigationController(new DeviceTest.Core.TestRunner.DeviceTestiOSRunner());
            Window.MakeKeyAndVisible();
#else
            HealthStore = new HKHealthStore();
            SetupHealthStoreForTabBarControllers();
#endif

            return(true);
        }
示例#9
0
        public bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            var read = new NSSet(HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate));

            var healthstore = new HKHealthStore();

            healthstore.RequestAuthorizationToShare(new NSSet(), read, (f, error) => {
                if (error != null)
                {
                    Console.WriteLine(@"{0} error", error);
                }
            });


            return(true);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            var massKey = HKQuantityTypeIdentifierKey.BodyMass;
            var massQuantityType = HKObjectType.GetQuantityType (massKey);

            var hks = new HKHealthStore ();
            hks.RequestAuthorizationToShare (new NSSet (new [] { massQuantityType }), new NSSet (), (success, error) => {
                Console.WriteLine ("Authorized:" + success);
                if (error != null) {
                    Console.WriteLine ("Authorization error: " + error);
                }
            });

            this.SaveWeight (hks);
        }
示例#11
0
        private void RequestAccessToHealthKit()
        {
            var healthStore = new HKHealthStore();

            var types = new NSSet(HKObjectType.GetWorkoutType(),
                                  HKSeriesType.WorkoutRouteType,
                                  HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned),
                                  HKQuantityType.Create(HKQuantityTypeIdentifier.DistanceWalkingRunning));

            healthStore.RequestAuthorizationToShare(types, types, (isSuccess, error) =>
            {
                if (!isSuccess)
                {
                    Console.WriteLine(error?.LocalizedDescription ?? "");
                }
            });
        }
        private void SaveWeight(HKHealthStore store)
        {
            var massKey = HKQuantityTypeIdentifierKey.BodyMass;
            var massQuantityType = HKObjectType.GetQuantityType (massKey);

            var currentMass = HKQuantity.FromQuantity (HKUnit.FromMassFormatterUnit(NSMassFormatterUnit.Kilogram), 77.0);

            var massSample = HKQuantitySample.FromType (massQuantityType, currentMass, new NSDate (), new NSDate (), new HKMetadata());

            store.SaveObject(massSample, (success, error) => {
                Console.WriteLine("Write succeeded: " + success);
                if(error != null)
                {
                    Console.WriteLine(error);
                }
            });
        }
示例#13
0
        public HealthKitService(
            IMeasureService measureService,
            IMvxLogProvider logProvider
            )
        {
            _log            = logProvider.GetLogFor <HealthKitService>();
            _measureService = measureService ?? throw new ArgumentNullException(nameof(measureService));
            _healthStore    = new HKHealthStore();

            AddCommand = ReactiveCommand.CreateFromTask <Measure>(
                v => AddSamples(GetQuantitySamples(v)));

            AddCommand.ThrownExceptions
            .Subscribe(e => _log.ErrorException("While add measure to health kit", e));

            EditCommand = ReactiveCommand.CreateFromTask <Measure>(EditMeasure);

            EditCommand.ThrownExceptions
            .Subscribe(e => _log.ErrorException("While edit measure to health kit", e));

            DeleteCommand = ReactiveCommand.CreateFromTask <Measure>(DeleteSamples);

            DeleteCommand.ThrownExceptions
            .Subscribe(e => _log.ErrorException("While deleting measure", e));

            MessageBus.Current
            .ListenIncludeLatest <MeasureAddedEvent>()
            .Select(v => v?.Value)
            .Where(v => v != null)
            .Where(v => GetStatus())
            .InvokeCommand(this, v => v.AddCommand);

            MessageBus.Current
            .ListenIncludeLatest <MeasureChangedEvent>()
            .Select(v => v?.Value)
            .Where(v => v != null)
            .Where(v => GetStatus())
            .InvokeCommand(this, v => v.EditCommand);

            MessageBus.Current
            .ListenIncludeLatest <MeasureDeletedEvent>()
            .Select(v => v?.Value)
            .Where(v => v != null)
            .Where(_ => GetStatus())
            .InvokeCommand(this, v => v.DeleteCommand);
        }
示例#14
0
        private void SaveWeight(HKHealthStore store)
        {
            var massKey          = HKQuantityTypeIdentifierKey.BodyMass;
            var massQuantityType = HKObjectType.GetQuantityType(massKey);

            var currentMass = HKQuantity.FromQuantity(HKUnit.FromMassFormatterUnit(NSMassFormatterUnit.Kilogram), 77.0);

            var massSample = HKQuantitySample.FromType(massQuantityType, currentMass, new NSDate(), new NSDate(), new HKMetadata());

            store.SaveObject(massSample, (success, error) => {
                Console.WriteLine("Write succeeded: " + success);
                if (error != null)
                {
                    Console.WriteLine(error);
                }
            });
        }
示例#15
0
        public bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Override point for customization after application launch.
            // If not required for your application you can safely delete this method

            var read = new NSSet(HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate));

            var healthstore = new HKHealthStore();

            healthstore.RequestAuthorizationToShare(new NSSet(), read, (f, error) => {
                if (error != null)
                {
                    Console.WriteLine(@"{0} error", error);
                }
            });

            return(true);
        }
示例#16
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var massKey          = HKQuantityTypeIdentifierKey.BodyMass;
            var massQuantityType = HKObjectType.GetQuantityType(massKey);

            var hks = new HKHealthStore();

            hks.RequestAuthorizationToShare(new NSSet(new [] { massQuantityType }), new NSSet(), (success, error) => {
                Console.WriteLine("Authorized:" + success);
                if (error != null)
                {
                    Console.WriteLine("Authorization error: " + error);
                }
            });

            this.SaveWeight(hks);
        }
示例#17
0
        public void StoreHeartRate(HKQuantity quantity)
        {
            var bpm = HKUnit.Count.UnitDividedBy(HKUnit.Minute);

            //Confirm that the value passed in is of a valid type (can be converted to beats-per-minute)
            if (!quantity.IsCompatible(bpm))
            {
                InvokeOnMainThread(() => ErrorMessageChanged(this, new GenericEventArgs <string>("Units must be compatible with BPM")));
            }

            var heartRateQuantityType = HKQuantityType.Create(HKQuantityTypeIdentifier.HeartRate);
            var heartRateSample       = HKQuantitySample.FromType(heartRateQuantityType, quantity, new NSDate(), new NSDate(), new HKMetadata());

            using (var healthKitStore = new HKHealthStore())
            {
                healthKitStore.SaveObject(heartRateSample, (success, error) =>
                {
                    InvokeOnMainThread(() =>
                    {
                        if (success)
                        {
                            HeartRateStored?.Invoke(this, new GenericEventArgs <Double>(quantity.GetDoubleValue(bpm)));
                        }
                        else
                        {
                            ErrorMessageChanged(this, new GenericEventArgs <string>("Save failed"));
                        }
                        if (error != null)
                        {
                            //If there's some kind of error, disable
                            Enabled = false;
                            ErrorMessageChanged(this, new GenericEventArgs <string>(error.ToString()));
                        }
                    });
                });
            }
        }
示例#18
0
        public void SetUpPermissions()
        {
            var distanceQuantityType          = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.DistanceWalkingRunning);
            var stepsQuantityType             = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.StepCount);
            var flightsQuantityType           = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.FlightsClimbed);
            var heightQuantityType            = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.Height);
            var heartRateQuantityType         = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.HeartRate);
            var nikeFuelQuantityType          = HKObjectType.GetQuantityType(HKQuantityTypeIdentifierKey.NikeFuel);
            var dateOfBirthCharacteristicType = HKObjectType.GetCharacteristicType(HKCharacteristicTypeIdentifierKey.DateOfBirth);
            var sexCharacteristicType         = HKObjectType.GetCharacteristicType(HKCharacteristicTypeIdentifierKey.BiologicalSex);
            var bloodTypeCharacteristicType   = HKObjectType.GetCharacteristicType(HKCharacteristicTypeIdentifierKey.BloodType);

            if (m_healthKitStore == null)
            {
                HealthKitStore = new HKHealthStore();
                m_healthKitStore.RequestAuthorizationToShare(new NSSet(new [] { distanceQuantityType, stepsQuantityType, flightsQuantityType, heartRateQuantityType }), new NSSet(new [] { (NSObject)distanceQuantityType, (NSObject)stepsQuantityType, (NSObject)flightsQuantityType, (NSObject)heightQuantityType, (NSObject)dateOfBirthCharacteristicType, (NSObject)sexCharacteristicType, (NSObject)bloodTypeCharacteristicType, (NSObject)nikeFuelQuantityType, (NSObject)bloodTypeCharacteristicType, (NSObject)heartRateQuantityType }), (success, error) => {
                    Console.WriteLine("Authorized:" + success);
                    if (error != null)
                    {
                        Console.WriteLine("Authorization error: " + error);
                    }
                });
            }
        }
 public HealthKitModule()
 {
     _healthStore = new HKHealthStore();
 }
 public HealthKitImplementation()
 {
     _healthStore = new HKHealthStore();
 }
示例#21
0
 protected iOSHealthKitProbe(HKObjectType objectType)
 {
     _objectType  = objectType;
     _healthStore = new HKHealthStore();
 }
示例#22
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            #region UI controls
            statusLabel      = new UILabel(new RectangleF(10, 30, 300, 30));
            statusLabel.Text = "waiting...";

            heartRateLabel           = new UILabel(new RectangleF(10, 70, 150, 30));
            heartRateLabel.Font      = UIFont.BoldSystemFontOfSize(36);
            heartRateLabel.TextColor = UIColor.Red;

            heartRateUnitLabel = new UILabel(new RectangleF(160, 70, 150, 30));

            deviceNameLabel = new UILabel(new RectangleF(10, 120, 300, 30));

            connectButton = UIButton.FromType(UIButtonType.System);
            connectButton.SetTitle("Connect", UIControlState.Normal);
            connectButton.SetTitle("searching...", UIControlState.Disabled);
            connectButton.Enabled        = false;
            connectButton.Frame          = new RectangleF(10, 160, 300, 30);
            connectButton.TouchUpInside += ConnectToSelectedDevice;

            permissionsLabel = new UILabel(new RectangleF(10, 200, 300, 60));

            storeData       = UIButton.FromType(UIButtonType.System);
            storeData.Frame = new RectangleF(10, 250, 300, 30);
            storeData.SetTitle("requires permission", UIControlState.Disabled);
            storeData.SetTitle("Store in HealthKit", UIControlState.Normal);
            storeData.Enabled        = false;
            storeData.TouchUpInside += (sender, e) => {
                UpdateHealthKit(heartRateLabel.Text);                 // pretty hacky :)
            };

            Add(statusLabel);
            Add(heartRateLabel);
            Add(heartRateUnitLabel);
            Add(deviceNameLabel);
            Add(connectButton);
            Add(permissionsLabel);
            Add(storeData);
            #endregion

            InitializeCoreBluetooth();

            #region HealthKit
            // https://gist.github.com/lobrien/1217d3cff7b29716c0d3
            // http://www.knowing.net/index.php/2014/07/11/exploring-healthkit-with-xamarin-provisioning-and-permissions-illustrated-walkthrough/

            healthKitStore = new HKHealthStore();
            //Permissions
            //Request HealthKit authorization
            var heartRateId   = HKQuantityTypeIdentifierKey.HeartRate;
            var heartRateType = HKObjectType.GetQuantityType(heartRateId);
            //Request to write heart rate, read nothing...
            healthKitStore.RequestAuthorizationToShare(new NSSet(new [] { heartRateType }), new NSSet(), (success, error) =>
                                                       InvokeOnMainThread(() => {
                if (success)
                {
                    //Whatever...
                    Console.WriteLine("RequestAuthorizationToShare: success");
                    permissionsLabel.Text = "HealthKit access is enabled!";
                    storeData.Enabled     = true;
                }
                else
                {
                    //Whatever...
                    Console.WriteLine("RequestAuthorizationToShare:  failed");
                    permissionsLabel.Text = "No permission to access HealthKit :-(";
                    storeData.Enabled     = false;
                }
                if (error != null)
                {
                    Console.WriteLine("HealthKit authorization error: " + error);
                }
            }));
            #endregion
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            #region UI controls
            statusLabel = new UILabel (new RectangleF(10, 30, 300, 30));
            statusLabel.Text = "waiting...";

            heartRateLabel = new UILabel(new RectangleF(10, 70, 150, 30));
            heartRateLabel.Font = UIFont.BoldSystemFontOfSize (36);
            heartRateLabel.TextColor = UIColor.Red;

            heartRateUnitLabel = new UILabel(new RectangleF(160, 70, 150, 30));

            deviceNameLabel = new UILabel(new RectangleF(10, 120, 300, 30));

            connectButton = UIButton.FromType (UIButtonType.System);
            connectButton.SetTitle ("Connect", UIControlState.Normal);
            connectButton.SetTitle ("searching...", UIControlState.Disabled);
            connectButton.Enabled = false;
            connectButton.Frame = new RectangleF (10, 160, 300, 30);
            connectButton.TouchUpInside += ConnectToSelectedDevice;

            permissionsLabel = new UILabel (new RectangleF (10, 200, 300, 60));

            storeData = UIButton.FromType (UIButtonType.System);
            storeData.Frame = new RectangleF (10, 250, 300, 30);
            storeData.SetTitle ("requires permission", UIControlState.Disabled);
            storeData.SetTitle ("Store in HealthKit", UIControlState.Normal);
            storeData.Enabled = false;
            storeData.TouchUpInside += (sender, e) => {
                UpdateHealthKit(heartRateLabel.Text); // pretty hacky :)
            };

            Add (statusLabel);
            Add (heartRateLabel);
            Add (heartRateUnitLabel);
            Add (deviceNameLabel);
            Add (connectButton);
            Add (permissionsLabel);
            Add (storeData);
            #endregion

            InitializeCoreBluetooth ();

            #region HealthKit
            // https://gist.github.com/lobrien/1217d3cff7b29716c0d3
            // http://www.knowing.net/index.php/2014/07/11/exploring-healthkit-with-xamarin-provisioning-and-permissions-illustrated-walkthrough/

            healthKitStore = new HKHealthStore();
            //Permissions
            //Request HealthKit authorization
            var heartRateId = HKQuantityTypeIdentifierKey.HeartRate;
            var heartRateType = HKObjectType.GetQuantityType (heartRateId);
            //Request to write heart rate, read nothing...
            healthKitStore.RequestAuthorizationToShare (new NSSet (new [] { heartRateType }), new NSSet (), (success, error) =>
                InvokeOnMainThread (() => {
                    if (success) {
                        //Whatever...
                        Console.WriteLine ("RequestAuthorizationToShare: success");
                        permissionsLabel.Text = "HealthKit access is enabled!";
                        storeData.Enabled = true;
                    } else {
                        //Whatever...
                        Console.WriteLine ("RequestAuthorizationToShare:  failed");
                        permissionsLabel.Text = "No permission to access HealthKit :-(";
                        storeData.Enabled = false;
                    }
                    if (error != null) {
                        Console.WriteLine ("HealthKit authorization error: " + error);
                    }
                }));
            #endregion
        }
 public HealthKitDataStore()
 {
     HealthStore = new HKHealthStore();
 }
示例#25
0
 public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
 {
     HealthStore = new HKHealthStore();
     SetupHealthStoreForTabBarControllers();
     return(true);
 }
示例#26
0
        public static async Task <IEnumerable <Record> > GetHealthRecords(HKHealthStore store, DateInterval dates)
        {
            var query = Query(store, dates);

            var queries = new[]
示例#27
0
 protected iOSHealthKitProbe(HKObjectType objectType)
 {
     _objectType = objectType;
     _healthStore = new HKHealthStore();
 }
示例#28
0
 public HealthStore(HKHealthStore healthStore)
 {
     _healthStore = healthStore;
 }
 public override async Task Execute()
 {
     store = new HKHealthStore();
     var height = await ReadCurrentHeightInMetres(store);
 }
示例#30
0
 public HeartRateMonitorImpl()
 {
     var store = new HKHealthStore();
     //store.GetRequestStatusForAuthorizationToShare(new Foundation.NSSet<HKSampleType>())
 }
示例#31
0
 public HealthDataWriter(HealthService healthService)
 {
     _healthService = healthService;
     _healthStore   = healthService.HealthStore;
 }
 public HealthKitService()
 {
     HealthStore = new HKHealthStore();
 }