我在我的应用中使用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)
}
答案 0 :(得分:1)
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 {
// ...
}
}
}