UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Network Status Check

Forums > Swift

Hey guy. I am having an issue with that function that I found on hackingwithswift.com

 func checkNetworkStatus() {
        let monitor = NWPathMonitor()

        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                print("internet")
            }
            else {
                print("no internet")
            }
        }
        let queue = DispatchQueue(label: "Monitor")
        monitor.start(queue: queue)

    }

when I turn the wifi off, it always return "internet" Then when I turn it on, it prints "no internet" and then a second after "internet".

What am I doing wrong? Or is there any better way to check the internet connection? I don't necessarily need to check it everytime the network status changes. Only when some button is tapped. Many thanks.

3      

Hi, well this is quite a complicated topic for a few reasons.

The behavior looks like you have Cellular data, and when you switch back to WiFi there is a small window when the internet does not work because it is switching connections...

As for checking if there is connection before doing something, the problem is that there might be but then disappear once you start the main work. I think there is even mention in the official Apple guidelines to not check for connection before doing other network related tasks. I think better idea is to just try it and report to user possible problems.

Imagine you implement checking network connection against some popular DNS, but maybe DNS will go down and user cannot continue, even though they have connection and your API is also working fine.

URLSession also has settings where it waits for connectivity for specified amount of time and does not fail straight away.

If you really want some checking, I would keep using the NWPathMonitor and when it indicates that connection is not available, then maybe show warning banner in your UI. Something like: "Looks like there might be a connection issue". But dont disable the button

3      

Hey Filip!

I am currently using Firebase in my project. The issue is (altough it's a good thing if you think about it) that Firebase is smart enough to not return an error when there is no connection but to wait with the execution until the connection appears. Therefore I cant return any error. While potential user may search through something that already does not exist in a firebase while the network is off...

3      

Use this instead, it will fix your issue...

if path.status != .unsatisfied { print("internet") }

3      

How can this be modified to continually check the network?

2      

The way I did it

// 3. If on WiFi then remove all data and fetch data
let queue = DispatchQueue.main // <- had to use main thread
monitor.start(queue: queue) 
monitor.pathUpdateHandler = { path in
      if path.status == .satisfied { // <- check to have Internet
          if path.isExpensive == false { // <- check to see if on WiFi network
              self.auditItems.removeAll(keepingCapacity: true)
              Task {
                  await self.fetch(for: auditURL)
              }
          }
      } else if path.status == .unsatisfied { // <- see if no internet
          if self.auditItems.isEmpty { // <- check to see if there was no item saved to FileManger
              self.noInternet = true // <- this change a bool so can display the they have no item and to check the internet connection
          }
      }

      self.monitor.cancel() // <- stop checking Internet connection
  }
}

This straight from my project

2      

@NigelGee. that looks great! I am super new to Swift and come from a C# background... so I take it Task is basically a threading method or library? At this time I do not have an app in mind just yet, but I did a lot of middleware coding for a larger .net app and I always was dealing with network related routines, many that needed threading .... thank you so much!!!!

2      

Task let you call an async func from sync func. As that what the await is about. I wanted the app to get a json from the internet but only if on WiFi, if not then use the json stored in FileManager

2      

@NigelGee, with the post at the top of the page, how best would Task be used? I tried something like

  Task {
              await checkNetworkStatus().monitor.start 
          }

          That didnt work so I need more study time lol

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.