我在应用程序中使用“可达性”类多次检查了互联网连接,
我想使用DI。
我该怎么办?
可达性等级:
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)
}
最佳答案
如果您不能在依赖实现之间切换,则依赖注入(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 {
// ...
}
}
}
关于swift - 使用具有可达性(互联网检查)类的依赖注入(inject)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34379644/