我为使用 Android SensorService 计算步数编写了一个接口和 android 实现。现在我正在尝试为 iOS 做同样的事情。除了返回两次之间的步数的https://github.com/xamarin/ios-samples/blob/master/PrivacyPrompts/PrivacyPrompts/PrivacyManager/MotionPrivacyManager.cs之外,我找不到关于此主题的任何代码示例间隔。但我需要实时监控步数。或者接近它。Android SensorService 有一些延迟,但它是实时执行的。我需要为 iOS 做同样的事情。有没有办法在iOS中做?
也许我需要制作一个 2 个时间框架的时间窗口并尝试以这种方式监控数据?但时间范围可能非常小,从一秒到五分钟。它甚至会起作用吗?
using CoreMotion;
using Foundation;
using UIKit;
namespace PrivacyPrompts
{
public class MotionPrivacyManager : IPrivacyManager, IDisposable
{
CMStepCounter stepCounter;
string motionStatus = "Indeterminate";
nint steps = 0;
CMMotionManager motionManger; // before iOS 8.0
CMPedometer pedometer; // since iOS 8.0
public MotionPrivacyManager ()
{
if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
pedometer = new CMPedometer ();
motionStatus = CMPedometer.IsStepCountingAvailable ? "Available" : "Not available";
} else {
stepCounter = new CMStepCounter ();
motionManger = new CMMotionManager ();
motionStatus = motionManger.DeviceMotionAvailable ? "Available" : "Not available";
}
}
public Task RequestAccess ()
{
var yesterday = NSDate.FromTimeIntervalSinceNow (-60 * 60 * 24);
if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
if(!CMPedometer.IsStepCountingAvailable)
return Task.FromResult<object> (null);
return pedometer.QueryPedometerDataAsync (yesterday, NSDate.Now)
.ContinueWith (PedometrQueryContinuation);
} else {
if (!motionManger.DeviceMotionAvailable)
return Task.FromResult<object> (null);
return stepCounter.QueryStepCountAsync (yesterday, NSDate.Now, NSOperationQueue.MainQueue)
.ContinueWith (StepQueryContinuation);
}
}
void PedometrQueryContinuation(Task<CMPedometerData> t)
{
if (t.IsFaulted) {
var code = ((NSErrorException)t.Exception.InnerException).Code;
if (code == (int)CMError.MotionActivityNotAuthorized)
motionStatus = "Not Authorized";
return;
}
steps = t.Result.NumberOfSteps.NIntValue;
}
void StepQueryContinuation(Task<nint> t)
{
if (t.IsFaulted) {
var code = ((NSErrorException)t.Exception.InnerException).Code;
if (code == (int)CMError.MotionActivityNotAuthorized)
motionStatus = "Not Authorized";
return;
}
steps = t.Result;
}
public string CheckAccess ()
{
return motionStatus;
}
public string GetCountsInfo()
{
return steps > 0 ? string.Format ("You have taken {0} steps in the past 24 hours", steps) : string.Empty;
}
public void Dispose ()
{
motionManger.Dispose ();
stepCounter.Dispose ();
}
}