iOS/SwiftUI

[iOS / SwiftUI] Check Network Connection Status with NWPathMonitor

TDCIAN 2021. 12. 30. 23:28

Hi! this is TDCIAN!

 

Let's find out about checking network connection status in SwiftUI!

 

Look at these codes!

 

(1) NetworkManager.swift

 

import Foundation
import Network // Let's import Network
class NetworkManager: ObservableObject {
let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "NetworkManager")
@Published var isConnected = true
// Image depends the network status.
var imageName: String {
return isConnected ? "wifi" : "wifi.slash"
}
// Text depends on the network status.
var connectionDescription: String {
if isConnected {
return "Internet connection looks good!"
} else {
return "It looks like you're not connected to the internet"
}
}
init() {
monitor.pathUpdateHandler = { path in
DispatchQueue.main.async {
self.isConnected = path.status == .satisfied
}
}
monitor.start(queue: queue)
}
// method working when you touch 'Check Status' button.
func startMonitoring() {
monitor.start(queue: queue)
monitor.pathUpdateHandler = { path in
self.isConnected = path.status == .satisfied
if path.usesInterfaceType(.wifi) {
print("Using wifi")
} else if path.usesInterfaceType(.cellular) {
print("Using cellular")
}
}
}
// method stop checking.
func stopMonitoring() {
monitor.cancel()
}
}

 

 

(2) ContentView.swift

 

import SwiftUI
struct ContentView: View {
@ObservedObject var networkManager = NetworkManager()
var body: some View {
Group {
if networkManager.isConnected {
// show main content
} else {
// show failed internet screen
}
}
ZStack {
Color(.systemBlue).ignoresSafeArea()
VStack {
Image(systemName: networkManager.imageName)
.resizable()
.scaledToFit()
.frame(width: 200, height: 200)
.foregroundColor(Color.white)
Text(networkManager.connectionDescription)
.font(.system(size: 18))
.foregroundColor(.white)
.padding()
Button(action: {
networkManager.startMonitoring()
}, label: {
Text("Check Status")
.padding()
.font(.headline)
.foregroundColor(Color(.systemBlue))
})
.frame(width: 140)
.background(Color.white)
.clipShape(Capsule())
.padding()
}
}
}
}

 

 

 

(3) In simulator

 

When network is connected

 

When network is not connected

 

 

Full source code: https://github.com/TDCIAN/NetworkManagerSwiftUI

 

GitHub - TDCIAN/NetworkManagerSwiftUI: based on: https://www.youtube.com/watch?v=YIx3e0xWKtk

based on: https://www.youtube.com/watch?v=YIx3e0xWKtk - GitHub - TDCIAN/NetworkManagerSwiftUI: based on: https://www.youtube.com/watch?v=YIx3e0xWKtk

github.com

 

Reference

(1) https://www.youtube.com/watch?v=YIx3e0xWKtk 

(2) https://magicmon.tistory.com/229