让我解释一下情况。我正在使用iPhone搜索信标。发现信标后,我会定期(1秒持续时间)将接收到的“ RSSI”值发送到Web服务器。我通过接收“ DiscoveredPeripheralCallback”启动计时器来做到这一点。尽管下面的方法最初会不断被调用,但是一旦实例化计时器,它就会停止并且只有计时器现在正在执行。我猜是与线程相关的问题导致了问题。
但是,如果我注释掉计时器,则一切正常,并且我在委托方法上获得了连续的回调,但是添加了一个计时器并在其中调用API会导致一些问题。
[Export("centralManager:didDiscoverPeripheral:advertisementData:RSSI:")]
public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
{
Console.WriteLine("METHOD - 1");
StartTimer();
string DeviceName = peripheral.Name;
discoverdBeacon.AddRawRSSI(RSSI.DoubleValue);
}
下面是我调用API的计时器方法。
private static void StartTimer()
{
// Create a timer with a one second interval.
if (rssiTimer == null)
{
Console.WriteLine("Timer Created");
rssiTimer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1.0), async delegate
{
Console.WriteLine("METHOD - 2");
var result = await SendBeaconDataToServer(179, 0, -81);
Console.WriteLine("Result = " + result);
});
rssiTimer.Fire();
}
}
// API方法
public static async Task<String> SendBeaconDataToServer(int majorId, int loopId, double rssiValue)
{
List<Peripheral> beaconsArray = new List<Peripheral>();
Peripheral item = new Peripheral();
item.major = majorId; //Keep major values in the range of 178-181
item.minor = loopId;//Keep minor value as zero for now.
item.rssi = rssiValue;
beaconsArray.Add(item);
BeaconInfo info = new BeaconInfo();
info.Panic = true;
info.TagType = true;
info.TagID = 101;
info.Anchors = beaconsArray.ToArray();
var result = await SharedWebClient.Instance.PostUserDetailsDataToServer(info, null);
return result;
}