首先是我的代码
func checkInternetConnection() {
reachability.whenReachable = { _ in
self.loadPost()
self.checkNewMessages()
self.slowView.frame.size.height = 0
self.slowView.isHidden = true
self.internetStatus.text = ""
self.slowView.layer.zPosition = 0
}
reachability.whenUnreachable = { _ in
self.refreshControl.endRefreshing()
self.slowView.backgroundColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
self.slowView.layer.zPosition = 1
self.slowView.frame.size.height = 40
self.slowView.isHidden = false
self.internetStatus.text = "Keine Internetverbindung!"
self.activityIndicatorView.stopAnimating()
self.Indicator.stopAnimating()
}
NotificationCenter.default.addObserver(self, selector: #selector(self.internetChanged(note:)), name: Notification.Name.reachabilityChanged, object: self.reachability)
do {
try self.reachability.startNotifier()
}catch {
print("error")
}
}
@objc func internetChanged(note: Notification) {
let reachability = note.object as! Reachability
if reachability.connection != .none {
self.slowView.backgroundColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
self.slowView.layer.zPosition = 1
self.slowView.frame.size.height = 40
self.slowView.isHidden = false
self.internetStatus.text = "Mit dem Internet verbunden!"
DispatchQueue.main.asyncAfter(deadline: .now() + 3 , execute: {
self.slowView.layer.zPosition = 0
self.slowView.frame.size.height = 0
})
} else {
print("kein internet")
}
}
我在viewDidLoad()中调用了checkInternetConnection()方法,它的工作正常,但是一旦我刷新了我的tableview,它就不会进入可达性闭包。
在handleRefresh()中(仅用于重新加载帖子)可以调用checkInternetConnection()方法,但不会触发任何代码,只会在刷新时出现问题,而不是初始加载。
我用这个视频作为参考: https://www.youtube.com/watch?v=wDZmz9IsB-8 有什么建议吗?
答案 0 :(得分:2)
我认为(但不是100%肯定)闭包whenReachable
和whenUnreachable
仅在适当的可达性变化发生时被调用;此外,他们可能会在分配时自动调用。因此,无论您多久调用一次checkInternetConnection
,除非设备离线/在线,否则闭包不会被重新执行。
要解决此问题,我建议改为使用可达性标志:
if reachability.isReachable {
// update view for reachable state
}
else {
// update view for unreachable state
}