TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Verify if phone can access internet even though connected to wifi.

Forums > Swift

In the available library/framework, can able to detect if the phone is connected to cellular/wifi. What if the phone connected to a wifi with no internet connection. How to determine this case. I've tried this code of checking if i can connect to google with URLSession. But it taking time and effecting user Experience.

    public static func canReachGoogle(_ result: ((Bool)-> Void)) {
        guard let url = URL(string: "https://8.8.8.8") else { return result(false) }

        var success = false
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            success = (error == nil)
        }

        task.resume()
        result(success)
    }

3      

Im curious, how should such a function improve user experience if you can handle the no connection error in the request you actually want to send? Both requests will fail and both requests will require a specific amount of time when failing. Furthermore, if your first check succeeds it doesn't necessarily mean your second request will.

3      

Certainly! The function provided, canReachGoogle, aims to check if a specific URL (Google's public DNS server in this case) is reachable. However, using this function may not significantly improve the user experience for a few reasons:

Redundant Checks: If you are using this function to determine whether you have an internet connection before sending an important request, it might lead to redundant checks. Both the check performed by this function and the subsequent request you want to send can fail independently. It means you might end up making two separate requests, both requiring time, when one could have sufficed.

Asynchronous Nature: The canReachGoogle function performs an asynchronous network request in the background. While it appears to provide an immediate result through the result closure, the actual network check takes time, and the result is returned later when the request is completed. This can be misleading to users who expect an instant response.

Multiple Failure Points: If the canReachGoogle function succeeds in checking the URL's reachability, it doesn't guarantee the success of the subsequent request you want to send. The network conditions might change between the two operations, leading to different outcomes.

Overall, using this function may not be the most efficient approach for improving the user experience when dealing with network-related tasks. Instead, it's generally better to handle potential network errors directly within the request you want to send and implement appropriate error handling mechanisms. By doing so, you can have more control over the process, optimize network requests, and provide a smoother user experience with clearer feedback on errors when they occur.

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

High qualitiy ChatGPT content is really improving our Internet experience.

4      

@Hatsuhira, is that a note of sarcasm, because from what I have seen of ChatGPT is that the answers are verbose, often inaccurate or misleading, and very often not answering the question posed.

3      

Sorry, should have marked it as such.

3      

Any insight into what the purpose is of these A.I.-generated posts? Are they bored individuals having fun by submitting random comments, or are they A.I. developers training their algorithms by assessing which posts generate human responses? (Interestingly, they mostly are not directing readers to third party websites as previous spammers did.)

The recent topic whose title includes Wordpress seems to be a first — both the initial question and answer are from chatbots. The bots are talking to each other!

3      

No, not really. But on my forums I delete such responses as soon as I see them. 99.99% of the time they're completely useless.

3      

make sure the Wi-Fi network is available and within range of the device. Check the network credentials: Check the stored network name and password and make sure they are correct and up to date. Restart the device: Restart the device and try to connect to the Wi-Fi network again.

3      

@divid  

Certainly, detecting the network connectivity status, especially distinguishing between cellular and Wi-Fi, can be achieved using the Network framework in iOS. To address the concern of Wi-Fi with no internet connection, you can use a combination of checking for network connectivity and attempting to reach a known host. Here's an example in Swift:

import Network

class NetworkMonitor {

static func startMonitoring(completion: @escaping (NetworkStatus) -> Void) {
    let monitor = NWPathMonitor()

    monitor.pathUpdateHandler = { path in
        let status = self.networkStatus(from: path)
        completion(status)
    }

    let queue = DispatchQueue(label: "NetworkMonitor")
    monitor.start(queue: queue)
}

private static func networkStatus(from path: NWPath) -> NetworkStatus {
    if path.status == .satisfied {
        if path.usesInterfaceType(.wifi) {
            return .wifi
        } else if path.usesInterfaceType(.cellular) {
            return .cellular
        } else {
            return .other
        }
    } else {
        return .noConnection
    }
}

}

enum NetworkStatus { case wifi case cellular case other case noConnection }

Usage: NetworkMonitor.startMonitoring { status in switch status { case .wifi: print("Connected to Wi-Fi") // Check for internet connectivity here if needed case .cellular: print("Connected to Cellular") // Check for internet connectivity here if needed case .other: print("Connected to other network") case .noConnection: print("No network connection") } }

This approach allows you to quickly determine the type of connection and whether there's a network connection without the delay of making an actual network request. You can further customize this based on your specific requirements.

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.