我想侦测网络状态,当网络状态改变时,在当前控制器中显示错误视图。但是使用协议存在问题。 这里是代码:如何通过协议显示视图?
private func networkingDetection() {
//This is the detective method in appdelegate
try! reachability.startNotifier()
reachability.whenReachable = { [weak self] _ in
DispatchQueue.main.async {
self?.currentViewController().hideNetworkingErrorView()
}
}
reachability.whenUnreachable = { [weak self] _ in
DispatchQueue.main.async {
self?.currentViewController().showNetworkingErrorView()
}
}
}
这里是协议
protocol NetworkingErrorProtocol {
// I want to show the default view if there is no networkingErrorView, and
when declare a custom view in controller, show the custom view.
//var networkingErrorView: UIView? { get }
func showNetworkingErrorView()
func hideNetworkingErrorView()
}
extension UIViewController: NetworkingErrorProtocol {
func showNetworkingErrorView() {
}
func hideNetworkingErrorView() {
}
}
谁能告诉我如何计算出来?这真的让我发疯。非常感谢。
为什么您使用协议而不是NSNotification中心? – KKRocks
什么是'currentViewController()'定义为? 'UIViewController'? – WCByrne
我同意。 'NSNotificationCenter'会是一个更干净的方式 – Paulw11