我开发了一个iOS应用程序,其中的数据由在线服务器提供,我正在使用Reachability 检查互联网连接的可用性,我现在需要做的是,创建一个如facebook messenger中的栏,当没有互联网连接可用时,它会立即出现在我的项目中的当前(每个)UIViewcontroller中,我如何才能做到这一点?
最佳答案
创建自己的窗口以消除条件。
import UIKit
import ReachabilitySwift
class HSWindow: UIWindow {
let sharedReachability = Reachability()!
// override point for subclass. Do not call directly
open override func becomeKey(){
sharedReachability.whenReachable = { reachability in
OperationQueue.main.addOperation({
self.removeRechabilityView()
})
}
sharedReachability.whenUnreachable = { reachability in
OperationQueue.main.addOperation({
self.addRechabilityView()
})
}
do {
try sharedReachability.startNotifier()
print("sharedReachability.startNotifier : Starting.....")
} catch {
print("sharedReachability.startNotifier : Unable to start notifier")
}
}
// override point for subclass. Do not call directly
open override func resignKey(){
sharedReachability.stopNotifier()
}
}
//add remove Rechability view
extension HSWindow {
func addRechabilityView(){
self.removeRechabilityView()
let view = HSRechabilityView(); //you any custom view that you want to show on internet connection loss
self.addSubview(view)
view.snp.makeConstraints { (make) in //instead of this you can give frame, I have used snapKit here
make.edges.equalTo(self)
}
}
func removeRechabilityView(){
for view in self.subviews { //find your view and remove when internet connected
if view is HSRechabilityView {
view.removeFromSuperview()
break;
}
}
}
}
在AppDelegate中-didFinishLaunching方法
self.window = HSWindow(frame: UIScreen.main.bounds) //user your custom window instead of default one, and this will do all magic without any code
self.window.makeKeyAndVisible()
如果你在这个流程中有任何问题,请告诉我