Home > Enterprise >  One time Internet Connection Check swift
One time Internet Connection Check swift

Time:10-16

I need to check the internet connection of a user for one time.

I thought of something like Device.isConnectedToTheInternet but I didn't find something similar... Every solution that if found was like an internet monitor over time, but that's not exactly what I need.

Someone ideas? Thanks, Boothosh

CodePudding user response:

As Rob Napier mentioned, it looks like the only thing readily available is the NWPathMonitor, which you can use to check the 'connectivity' to a certain location, like www.google.com, or something else that would be relatively trustworthy to be available 24/7, or just the URL you are about to try and use. Here is a short HackingWithSwift tutorial for NWPathMonitor.

I know this isn't exactly your current situation, but in my projects (and a lot of peoples projects) using an API like AlamoFire is pretty common, and has a ton of usefulness for creating GET/PUT/POST/DELETE requests and of course, has a NetworkReachabilityManager which can be used to make a convenient global function for a simple true/false result for 'isConnectedToInternet' like this:

 /*
 Connectivity
 Struct
 Utilizes AlamoFire to check for network availability.
 isConnectedToInternet should return true in all cases the phone has access (Cellular, No cellular   wifi, Cellular   wifi, wifi)
*/
struct Connectivity {
    static let sharedInstance = NetworkReachabilityManager()!
    static var isConnectedToInternet:Bool {
        let connected = self.sharedInstance.isReachable
        return connected
    }
}//end Connectivity

CodePudding user response:

See NWPathMonitor().currentPath. It will tell you the current path. This is only occasionally useful, since "connected to the internet" is not a meaningful condition. There is not concrete definition of "the internet." But you can use the NWPath to answer some questions you probably are looking for. The fact that there is an NSPath available does not mean that you can actually connect to something on "the internet." The only way to know that is to send a packet and get a packet back. So if your real question is "can I connect to a specific host," then you're going to need to send packets to that host (and that still won't prove that you can send packets to the host in the future).

All that said, there is a little UI-level usefulness to asking "if I tried to connect, would it certainly fail?" And currentPath can help you answer that. It just can't tell you if it would succeed.

  • Related