Swift:为所有视图添加离线栏,例如在facebook messenger中

时间:2018-06-12 13:29:48

标签: ios swift uiviewcontroller reachability

我开发了一个iOS应用程序,其中的数据由在线服务器提供,我正在使用Reachability 来检查互联网连接的可用性,我现在需要做什么,创建一个条形图,如在facebook messenger中当没有可用的互联网连接时,我立即出现在我项目中的当前(每个)UIViewcontroller中,我该如何实现?

2 个答案:

答案 0 :(得分:0)

创建自己的窗口以消除条件。

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()
  

如果您在此流程中有任何问题,请告诉我

答案 1 :(得分:0)

您可以创建UIWindow,而不是对BaseViewController进行子类化,并且所有视图控制器都会继承它。

在视图控制器中,您可以使用view属性的安全区域将自定义视图放在正确的位置。

要显示该视图并将其显示在所有视图控制器中,您可以检查互联网连接并使用NotificationCenter在网络状态发生变化时通知所有视图控制器。