Checking Internet Connectivity in Swift — A Simple and Reliable Solution
Hello everyone! I'm a beginner in Swift and iOS development. I'm writing an app that loads data from the network, but I've run into a problem: if the internet is disconnected, the app just hangs or crashes with an error. I need to check for internet connectivity before making a request.
I found Apple's old Reachability library, but it's in Objective-C and, as I understand, is already outdated. I tried using it via a bridging header but got confused. I've also heard about NWPathMonitor from Network.framework, but I don't understand how to properly integrate it into my app.
Here's an example of my code where I try to load data without checking:
```swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
func fetchData() {
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data
No answers yet.
Log in to leave an answer