When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this?
The code:
import Foundation
impo
struct Connectivity {
static let sharedInstance = NetworkReachabilityManager()!
static var isConnectedToInternet:Bool {
return self.sharedInstance.isReachable
}
}
Now call it
if Connectivity.isConnectedToInternet{
call_your_methods_here()
}else{
show_alert_for_noInternet()
}
While it may not directly determine whether the phone is connected to a network, the simplest(, cleanest?) solution would be to 'ping' Google, or some other server, (which isn't possible unless the phone is connected to a network):
private var urlSession:URLSession = {
var newConfiguration:URLSessionConfiguration = .default
newConfiguration.waitsForConnectivity = false
newConfiguration.allowsCellularAccess = true
return URLSession(configuration: newConfiguration)
}()
public func canReachGoogle() -> Bool
{
let url = URL(string: "https://8.8.8.8")
let semaphore = DispatchSemaphore(value: 0)
var success = false
let task = urlSession.dataTask(with: url!)
{ data, response, error in
if error != nil
{
success = false
}
else
{
success = true
}
semaphore.signal()
}
task.resume()
semaphore.wait()
return success
}
If you're concerned that the server may be down or may block your IP, you can always ping multiple servers in a similar fashion and return whether any of them are reachable. Or have someone set up a dedicated server just for this purpose.
Although it does not directly answers your question, I would like to mention Apple recentely had this talk:
https://developer.apple.com/videos/play/wwdc2018/714/
At around 09:55 he talks about doing this stuff you are asking about:
However, this has a few pitfalls:
The following points are some best practices according to Apple:
waitsForConnectivity
to true (https://developer.apple.com/documentation/foundation/urlsessionconfiguration/2908812-waitsforconnectivity)taskIsWaitingForConnectivity
(https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate/2908819-urlsession). This is Apple's recommended way to check for connectivity, as mentioned in the video at 33:25.According to the talk, there shouldn't be any reason to pre-check whetever you got internet connection or not, since it may not be accurate at the time you send your request to the server.