我正在尝试删除我的 Xamarin.iOS 应用添加的 HKObject。我能够成功保存和查询 Apple HealthKit 中的数据,但 HKHealthStore.DeleteObjectAsync(和 HKHealthStore.DeleteObject)方法在运行后消失了。没有返回错误并且下一行代码没有被命中。以下是可用于重新创建问题的示例代码。由于没有响应或异常,我不确定从哪里开始尝试解决此问题。有谁知道我怎样才能让 DeleteObjectAsync(或 DeleteObject)在 Xamarin.iOS 中工作?
我正在使用的 AsyncHelpers 类的代码可以在这里找到。
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);
}
}
}