#### 1.使用NEVPNManager框架检查VPN连接状态:
```
import NetworkExtension
let manager = NEVPNManager.shared()
switch manager.connection.status {
case .connected:
print("VPN is connected")
case .disconnected:
print("VPN is disconnected")
case .connecting:
print("VPN is connecting")
case .disconnecting:
print("VPN is disconnecting")
case .invalid:
print("VPN is invalid")
@unknown default:
print("Unknown VPN status")
}
```
#### 2.使用SCNetworkReachability框架检查VPN连接状态:
```
import SystemConfiguration
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
if flags.contains(.reachable) && !flags.contains(.isWWAN) {
if flags.contains(.connectionRequired) || flags.contains(.transientConnection) {
// VPN is connecting or disconnecting
} else if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) || flags.contains(.interventionRequired) {
// VPN is connected
} else {
// VPN is disconnected
}
} else {
// No internet connection
}
}
```
网友评论