如何在swift中的单例中使用此代码?

时间:2016-11-15 17:27:49

标签: ios singleton swift3 alamofire

我在这里找到了这个代码。现在我想知道如何在单身中使用它。我的理解是,如果我在单例中使用此代码,如果网络状态发生变化,我会被注意到。

 func startNetworkReachabilityObserver() {
    let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")
    reachabilityManager?.listener = { status in

        switch status {

        case .NotReachable:
            print("The network is not reachable")

        case .Unknown :
            print("It is unknown whether the network is reachable")

        case .Reachable(.EthernetOrWiFi):
            print("The network is reachable over the WiFi connection")

        case .Reachable(.WWAN):
            print("The network is reachable over the WWAN connection")

        }
    }

    // start listening
    reachabilityManager?.startListening()
}

2 个答案:

答案 0 :(得分:1)

只要您保留reachabilityManager

的引用,就可以使用单例
class NetworkStatus {
static let sharedInstance = NetworkStatus()

private init() {}

let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")

func startNetworkReachabilityObserver() {
    reachabilityManager?.listener = { status in

        switch status {

        case .notReachable:
            print("The network is not reachable")

        case .unknown :
            print("It is unknown whether the network is reachable")

        case .reachable(.ethernetOrWiFi):
            print("The network is reachable over the WiFi connection")

        case .reachable(.wwan):
            print("The network is reachable over the WWAN connection")

        }
    }
    reachabilityManager?.startListening()
}

}

所以你可以像这样使用它:

let networkStatus = NetworkStatus.sharedInstance

override func awakeFromNib() {
    super.awakeFromNib()
    networkStatus.startNetworkReachabilityObserver()
}

如果您的网络状态发生任何变化,系统会通知您。

答案 1 :(得分:0)

将变量作为属性提升到类中。添加静态共享属性以使您的类成为单例。

d,e,f

默认情况下,静态属性是惰性的,因此当您调用ReachabilityManager.shared.startListening()时,它将首次实例化单例,后续调用将使用现有的共享实例。