我正在使用Alamofire NetworkReachabilityManager来管理我的连接,如下所示。
let reachabilityManager = NetworkReachabilityManager()
reachabilityManager?.listener = { [weak self] status in
switch status {
case .notReachable:
self?.connectionType = .notReachable
break
case .unknown:
self?.connectionType = .notReachable
break
case .reachable(.ethernetOrWiFi):
self?.connectionType = .wifi
break
case .reachable(.wwan):
self?.connectionType = .cellular
break
}
public enum ReachabilityStatus {
case unknown
case notReachable
case wifi
case cellular
}
当我启动应用程序本身时,我收到此回调但我不希望这个回调只有在网络连接发生变化时才需要回调。
我该如何解决这个问题?
答案 0 :(得分:2)
如何创建变量来存储先前的状态,并在第一次调用时检查变量是否为nil。之后,您可以随时检查状态是否已更改。
<div style="width:100%">
<div id="id1" style="width:40%;float:left;background-color:green;position:relative">
float-left
</div>
<div id="id2" style="width:60%;float:right;background-color:yellow;position:relative">
float-right
<div id="id3" style="position:relative;display:inline-block">
button1
</div>
<div id="id4" style="position:absolute;right:0px;top:0">
button2
</div>
</div>
<div style="clear:both"></div>
</div>
答案 1 :(得分:0)
您可以在延迟一段时间后添加监听器。因此,当应用程序启动时实例化NetworkReachabilityManager时,侦听器应为nil
let reachabilityManager = NetworkReachabilityManager()
var previousStatus: ReachabilityStatus? = nil
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
reachabilityManager?.listener = { [weak self] status in
if let p = self.previousStatus, p == status {
return // status hasn't changed
} else {
// status is nil
self.previousStatus = status
return
}
switch status {
case .notReachable:
self?.connectionType = .notReachable
break
case .unknown:
self?.connectionType = .notReachable
break
case .reachable(.ethernetOrWiFi):
self?.connectionType = .wifi
break
case .reachable(.wwan):
self?.connectionType = .cellular
break
}
})
编辑:我已经测试了这段代码。它有效。