Check your internet connection with Alamofire

Introduction

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.

Use NetworkReachabilityManager

Alamofire has a class called `` `NetworkReachabilityManager``` by default. This time, use that to check the connection status. Reference

How to use

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

Check your internet connection with Alamofire
Install GitLab on CentOS 8 with no internet connection
[Docker] Connection with MySQL
Check compliance with object-oriented exercise
Check CSV value with RSpec
[Template] MySQL connection with Java
Try DB connection with Java
Automate your work with Rake
Integer check method with ruby
Check performance quickly with irb
Check https connection in Java
Tune your query with EXPLAIN
VisualVM (JMX connection) with Kubernetes