I want to check if the device is connected to internet. For it, I wait until i get a result (true or false). Here is my code:
import Foundation
import Network
let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "Monitor")
var connected = false
func checkConnection(completion:@escaping (Bool) -> () ) {
DispatchQueue.main.async {
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
connected = true
} else {
connected = false
}
}
monitor.start(queue: queue)
completion(true)
}
}
checkConnection { (status) in
if status {
print(connected)
}
}
I don't understand why it doesn't work. I expected the value of connected
changes, depending on whether I am connected to the internet or not. Instead of that, the value of connected
remains equal to false
.
Does somebody have an idea ? Thank you
I found another way, simpler to do it: This class verify the internet connection (wifi or cellular) :
import SystemConfiguration
public class CheckInternet{
class func Connection() -> Bool{
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
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(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
// Working for Cellular and WIFI
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
}
Then, in your code you check (and wait for) the connection:
func checkConnection(completion:@escaping (Bool) -> () ) {
DispatchQueue.main.async {
if CheckInternet.Connection(){
print("Internet connection is on.")
self.go = true
} else {
self.go = false
print("There's no internet connection.")
}
completion(true)
}
}
checkConnection { (status) in
if status {
if self.go {
// your code
} else {
// your code
}
}
}