When making an API request with Alamofire, it was necessary to throw an error if the terminal was not connected to the Internet. It is a summary of what I investigated at that time.
Alamofire has a class called `` `NetworkReachabilityManager``` by default. This time, use that to check the connection status. Reference
Part ① Solid The amount of code is small, but it is hard to read
import Alamofire
if let isConnected = NetworkReachabilityManager()?.isReachable, !isConnected {
print("Disconnect")
}
Part 2 Define a class Easy to see
import Alamofire
class ConnectCheck {
func isConnectedNetwork() -> Bool {
return NetworkReachabilityManager()?.isReachable ?? false
}
}
When to use
if ConnectCheck.isConnectedNetwork {
print("Connect")
} else {
print("Disconnect")
}
It was like this.
Recommended Posts