使用具有可达性的依赖注入(因特网检查)类?

时间:2015-12-20 09:36:57

标签: swift design-patterns dependency-injection

我在我的应用中使用Reachability类

多次检查互联网连接

我想使用DI。

我怎么能这样做?

Reachabilty class:

public class Reachability {
class func isConnectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }
    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
}

1 个答案:

答案 0 :(得分:1)

如果您不能在依赖项实现之间切换,那么依赖注入(DI)会有一点意义,因此我们将为依赖项引入协议。对你的班级进行一些修改后,我会用DI模式看到它如下。

protocol Reachability {
    var connectedToNetwork: Bool { get }
}

class DefaultReachability: Reachability {

    var connectedToNetwork: Bool {
        // ...
    }

}

// Example of a dependend class
class Some {

    let reachability: Reachability

    init(reachability: Reachability) {
        self.reachability = reachability // Now it is dependency
    }

    func action() {
        if reachability.connectedToNetwork {
            // ...
        } else {
            // ...
        }
    }

}