You can try as Muhammad says.
I suggest the following code which is very easy to maintain. Copy paste the following code to a file and try yourself.
import Foundation
import SystemConfiguration
class Network {
// Declarations
static let shared = Network()
// Check has Network
func isConnected() -> Bool {
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()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
Create a swift file and put the above code on that file.
Whenever you want to check the network status just use the following code
if Network.shared.isConnected() {
print("Network available")
} else {
print("Not connected")
}