1
How can I check in my app (swift
) if the user has access to internet?
1
How can I check in my app (swift
) if the user has access to internet?
2
Assuming you have a class for useful methods for static access, it would be more or less like a class Functions.swift
:
import SystemConfiguration
struct Functions {
static 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)
}
}
And then, in your visualization classes, you would have something like this (with Swift, in this situation you do not need to import the class Functions
):
if Functions.isConnectedToNetwork() {
print("tem internet")
} else {
print("nao tem internet")
}
The return is a boolean
, then it says whether or not there is access to the internet, be it by wifi or cellular network.
Browser other questions tagged ios swift
You are not signed in. Login or sign up in order to post.
That code works perfectly here.
– Paulo Rodrigues
@Paulorodrigues I create a class and call a method or I can put in a class I already have (remembering that the one I have inherits viewController) ?
– Augusto Furlan
The good thing is you create this class and then call this method being static, like
Reachability. isConnectedToNetwork ()
. So you can use it anywhere, not just in this your Viewcontroller.– Paulo Rodrigues
@Paulorodrigues sorry my ignorance how could I do this p import? because I created it in a Swift file and it did not allow me to import it (like import) ? and this code returns me true or false to the internet ?
– Augusto Furlan
In Reachability (https://github.com/ashleymills/Reachability.swift) you can monitor the internet if it falls... and also know if it is connected to Wifi or 3G :)
– Lucas Eduardo