为什么我的HKHealthStore.DeleteObjectAsync方法没有执行并返回Xamarin中的对象?

时间:2017-06-18 01:37:30

标签: ios xamarin.ios health-kit hksamplequery

我正在尝试删除由我的Xamarin.iOS应用添加的HKObject。我能够成功保存并查询Apple HealthKit中的数据,但HKHealthStore.DeleteObjectAsync(和HKHealthStore.DeleteObject)方法在运行后会消失。没有返回错误,下一行代码没有被命中。以下是可用于重新创建问题的示例代码。由于没有响应或异常,我不知道从哪里开始尝试解决此问题。有谁知道如何在Xamarin.iOS中使用DeleteObjectAsync(或DeleteObject)?

我正在使用的AsyncHelpers类的代码可以找到here

Zipped Project

public partial class ViewController : UIViewController
{
    string Id => "54b50df8-35ab-4f53-ac19-0ad0c3d3551a";

    protected ViewController(IntPtr handle) : base(handle)
    {
    }

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

    partial void AddUsage(UIButton sender) //<- Button TouchUpInside
    {
        Tuple<HKUnit, double> entryItems = new Tuple<HKUnit, double>(HKUnit.CreateLiterUnit(HKMetricPrefix.Milli), 10);

        HKQuantity quantity = HKQuantity.FromQuantity(entryItems.Item1, entryItems.Item2);
        HKQuantityType qType = HKQuantityType.Create(HKQuantityTypeIdentifier.DietaryWater);
        HKMetadata metadata = new HKMetadata { ExternalUuid = Id };
        HKQuantitySample sample = HKQuantitySample.FromType(qType, quantity, new NSDate(), new NSDate(), metadata);
        using (HKHealthStore store = new HKHealthStore())
        {
            AsyncHelpers.RunSync(async () =>
            {
                Tuple<bool, NSError> saveResult = await store.SaveObjectAsync(sample);
            });

        }
    }

    partial void DeleteUsage(UIButton sender) //<- Button TouchUpInside
    {
        using (HKHealthStore store = new HKHealthStore())
        {
            NSCalendar calendar = NSCalendar.CurrentCalendar;
            NSDate now = new NSDate();
            NSDateComponents components = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, now);
            NSDate startDate = calendar.DateByAddingUnit(NSCalendarUnit.Day, -2, now, NSCalendarOptions.None);
            NSDate endDate = calendar.DateByAddingUnit(NSCalendarUnit.Day, 1, now, NSCalendarOptions.None);
            HKQuantityType qType = HKQuantityType.Create(HKQuantityTypeIdentifier.DietaryWater);
            NSPredicate pred = HKQuery.GetPredicateForSamples(startDate, endDate, HKQueryOptions.None);
            HKSampleQuery query = new HKSampleQuery(qType, pred, 0, null, (sampleQuery, results, error) =>
            {
                HKObject[] arr = results.Where(r => r.Metadata.ExternalUuid == Id).ToArray();
                if (arr.Length > 0)
                {
                    AsyncHelpers.RunSync(async () =>
                        {
                            Tuple<bool, NSError> deleteResult = await store.DeleteObjectAsync(arr.First()); // <- The breakpoint on this line is hit
                            string s = "s"; // <- The breakpoint on this line isn't ever hit
                        });
                }
            });
            store.ExecuteQuery(query);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

夫妻俩:

1)按HealthKit docs

  

每个应用只需要一个HealthKit商店。这些是长寿命的物体。创建商店一次,并保留一个参考供以后使用。

因此,您不应该将您的HKHealthStore包装在使用声明中。

2)你的AsyncHelpers正在吃异常或做其他可能因为你因为你在尝试删除时在后台线程上回调的上下文中而设置的其他东西。

此更新的代码有效:

public partial class ViewController : UIViewController
{
    HKHealthStore Store = new HKHealthStore();

    string Id => "54b50df8-35ab-4f53-ac19-0ad0c3d3551a";

    protected ViewController(IntPtr handle) : base(handle)
    {
    }

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

    partial void AddUsage(UIButton sender) //<- Button TouchUpInside
    {
        Tuple<HKUnit, double> entryItems = new Tuple<HKUnit, double>(HKUnit.CreateLiterUnit(HKMetricPrefix.Milli), 10);

        HKQuantity quantity = HKQuantity.FromQuantity(entryItems.Item1, entryItems.Item2);
        HKQuantityType qType = HKQuantityType.Create(HKQuantityTypeIdentifier.DietaryWater);
        HKMetadata metadata = new HKMetadata { ExternalUuid = Id };
        HKQuantitySample sample = HKQuantitySample.FromType(qType, quantity, new NSDate(), new NSDate(), metadata);

        Task.Run(async () =>
        {
            try
            {
                var save = await Store.SaveObjectAsync(sample);
                System.Diagnostics.Debug.WriteLine($"{save}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"{ex}");
            }
        });
    }

    partial void DeleteUsage(UIButton sender) //<- Button TouchUpInside
    {
        NSCalendar calendar = NSCalendar.CurrentCalendar;
        NSDate now = new NSDate();
        NSDateComponents components = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, now);
        NSDate startDate = calendar.DateByAddingUnit(NSCalendarUnit.Day, -2, now, NSCalendarOptions.None);
        NSDate endDate = calendar.DateByAddingUnit(NSCalendarUnit.Day, 1, now, NSCalendarOptions.None);
        HKQuantityType qType = HKQuantityType.Create(HKQuantityTypeIdentifier.DietaryWater);
        NSPredicate pred = HKQuery.GetPredicateForSamples(startDate, endDate, HKQueryOptions.None);
        HKSampleQuery query = new HKSampleQuery(qType, pred, 0, null, (sampleQuery, results, error) =>
        {
            HKObject[] arr = results.Where(r => r.Metadata.ExternalUuid == Id).ToArray();
            if (arr.Length > 0)
            {
                Task.Run(async () =>
                {
                    try
                    {
                        var delete = await Store.DeleteObjectAsync(arr.First());
                        System.Diagnostics.Debug.WriteLine($"{delete}");
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"{ex}");
                    }
                });
            }
        });
        Store.ExecuteQuery(query);
    }
}