我想每次网络状态更改时只执行一次方法callFormDataPushOnBackground。但现在每当网络状态由于收听者而改为在线“.reachable”多次调用时。 如何只允许一个电话并丢弃其余电话?我尝试使用listenerQueue.asyncAfter,但它无效。
任何帮助表示感谢。
func rechability()->(Isconected:Bool,status:Error?){
var conectivity:Bool = false
var statusError:Error?
var offlinePushFlag = true
manager?.listener = { status in
switch status {
case .notReachable:
conectivity = false
statusError = typeError.eNotRechable
offlinePushFlag = true
self.updatetheSyncLable()
print("The network is not reachable")
case .unknown :
statusError = typeError.eUnknown
conectivity = false
offlinePushFlag = true
self.updatetheSyncLable()
print("It is unknown whether the network is reachable")
case .reachable(.ethernetOrWiFi):
statusError = typeError.eRechable
conectivity = true
self.updatetheSyncLable()
var x = 1
self.manager?.listenerQueue.asyncAfter(deadline: .now() + .milliseconds(10000 * x + 2), execute: {
x = x + 1
if offlinePushFlag == true{
offlinePushFlag = false
print("I calledonlyoneTimeWIFI")
self.callFormDataPushOnBackground()
}
})
print("The network is reachable over the WiFi connection")
case .reachable(.wwan):
statusError = typeError.eWanRechable
conectivity = true
self.updatetheSyncLable()
if offlinePushFlag == true{
print("I calledonlyoneTimeWWAN")
offlinePushFlag = false
self.callFormDataPushOnBackground()
}
print("The network is reachable over the WWAN connection")
}
}
manager?.startListening()
return (conectivity,statusError)
}
答案 0 :(得分:1)
如果我理解正确,您可以使用 DispatchSemaphore 来确保在下一次调用开始之前完成一次调用
public abstract class StubsCreatorAbstract
{
public Mock<T> GenerateObject<T>() where T : class
{
var mock = new Mock<T>();
return mock;
}
public Mock<D> SetupValue<T, D>(Mock<D> stub, string nameOfField, T value) where D : class
{
var field = typeof(D).GetProperty(nameOfField);
if (field == null)
{
throw new ArgumentException("Field do not exist");
}
field.SetValue(stub.Object, value);
return stub;
}
}
注意,您应该小心不要阻止主队列,因为这会导致您的应用无响应。
像:
let semaphore = DispatchSemaphore(value:1)
manager?.listener = { status in
// some code
// you completed your work here
self.semaphore.signal()
}