added iOS source code
[wl-app.git] / iOS / Pods / Alamofire / Source / NetworkReachabilityManager.swift
1 //
2 //  NetworkReachabilityManager.swift
3 //
4 //  Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/)
5 //
6 //  Permission is hereby granted, free of charge, to any person obtaining a copy
7 //  of this software and associated documentation files (the "Software"), to deal
8 //  in the Software without restriction, including without limitation the rights
9 //  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 //  copies of the Software, and to permit persons to whom the Software is
11 //  furnished to do so, subject to the following conditions:
12 //
13 //  The above copyright notice and this permission notice shall be included in
14 //  all copies or substantial portions of the Software.
15 //
16 //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 //  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 //  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 //  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 //  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 //  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 //  THE SOFTWARE.
23 //
24
25 #if !os(watchOS)
26
27 import Foundation
28 import SystemConfiguration
29
30 /// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
31 /// WiFi network interfaces.
32 ///
33 /// Reachability can be used to determine background information about why a network operation failed, or to retry
34 /// network requests when a connection is established. It should not be used to prevent a user from initiating a network
35 /// request, as it's possible that an initial request may be required to establish reachability.
36 public class NetworkReachabilityManager {
37     /// Defines the various states of network reachability.
38     ///
39     /// - unknown:      It is unknown whether the network is reachable.
40     /// - notReachable: The network is not reachable.
41     /// - reachable:    The network is reachable.
42     public enum NetworkReachabilityStatus {
43         case unknown
44         case notReachable
45         case reachable(ConnectionType)
46     }
47
48     /// Defines the various connection types detected by reachability flags.
49     ///
50     /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi.
51     /// - wwan:           The connection type is a WWAN connection.
52     public enum ConnectionType {
53         case ethernetOrWiFi
54         case wwan
55     }
56
57     /// A closure executed when the network reachability status changes. The closure takes a single argument: the
58     /// network reachability status.
59     public typealias Listener = (NetworkReachabilityStatus) -> Void
60
61     // MARK: - Properties
62
63     /// Whether the network is currently reachable.
64     public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
65
66     /// Whether the network is currently reachable over the WWAN interface.
67     public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) }
68
69     /// Whether the network is currently reachable over Ethernet or WiFi interface.
70     public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) }
71
72     /// The current network reachability status.
73     public var networkReachabilityStatus: NetworkReachabilityStatus {
74         guard let flags = self.flags else { return .unknown }
75         return networkReachabilityStatusForFlags(flags)
76     }
77
78     /// The dispatch queue to execute the `listener` closure on.
79     public var listenerQueue: DispatchQueue = DispatchQueue.main
80
81     /// A closure executed when the network reachability status changes.
82     public var listener: Listener?
83
84     private var flags: SCNetworkReachabilityFlags? {
85         var flags = SCNetworkReachabilityFlags()
86
87         if SCNetworkReachabilityGetFlags(reachability, &flags) {
88             return flags
89         }
90
91         return nil
92     }
93
94     private let reachability: SCNetworkReachability
95     private var previousFlags: SCNetworkReachabilityFlags
96
97     // MARK: - Initialization
98
99     /// Creates a `NetworkReachabilityManager` instance with the specified host.
100     ///
101     /// - parameter host: The host used to evaluate network reachability.
102     ///
103     /// - returns: The new `NetworkReachabilityManager` instance.
104     public convenience init?(host: String) {
105         guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
106         self.init(reachability: reachability)
107     }
108
109     /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
110     ///
111     /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
112     /// status of the device, both IPv4 and IPv6.
113     ///
114     /// - returns: The new `NetworkReachabilityManager` instance.
115     public convenience init?() {
116         var address = sockaddr_in()
117         address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
118         address.sin_family = sa_family_t(AF_INET)
119
120         guard let reachability = withUnsafePointer(to: &address, { pointer in
121             return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) {
122                 return SCNetworkReachabilityCreateWithAddress(nil, $0)
123             }
124         }) else { return nil }
125
126         self.init(reachability: reachability)
127     }
128
129     private init(reachability: SCNetworkReachability) {
130         self.reachability = reachability
131         self.previousFlags = SCNetworkReachabilityFlags()
132     }
133
134     deinit {
135         stopListening()
136     }
137
138     // MARK: - Listening
139
140     /// Starts listening for changes in network reachability status.
141     ///
142     /// - returns: `true` if listening was started successfully, `false` otherwise.
143     @discardableResult
144     public func startListening() -> Bool {
145         var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
146         context.info = Unmanaged.passUnretained(self).toOpaque()
147
148         let callbackEnabled = SCNetworkReachabilitySetCallback(
149             reachability,
150             { (_, flags, info) in
151                 let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue()
152                 reachability.notifyListener(flags)
153             },
154             &context
155         )
156
157         let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
158
159         listenerQueue.async {
160             self.previousFlags = SCNetworkReachabilityFlags()
161             self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
162         }
163
164         return callbackEnabled && queueEnabled
165     }
166
167     /// Stops listening for changes in network reachability status.
168     public func stopListening() {
169         SCNetworkReachabilitySetCallback(reachability, nil, nil)
170         SCNetworkReachabilitySetDispatchQueue(reachability, nil)
171     }
172
173     // MARK: - Internal - Listener Notification
174
175     func notifyListener(_ flags: SCNetworkReachabilityFlags) {
176         guard previousFlags != flags else { return }
177         previousFlags = flags
178
179         listener?(networkReachabilityStatusForFlags(flags))
180     }
181
182     // MARK: - Internal - Network Reachability Status
183
184     func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
185         guard isNetworkReachable(with: flags) else { return .notReachable }
186
187         var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
188
189     #if os(iOS)
190         if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
191     #endif
192
193         return networkStatus
194     }
195
196     func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool {
197         let isReachable = flags.contains(.reachable)
198         let needsConnection = flags.contains(.connectionRequired)
199         let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic)
200         let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired)
201
202         return isReachable && (!needsConnection || canConnectWithoutUserInteraction)
203     }
204 }
205
206 // MARK: -
207
208 extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
209
210 /// Returns whether the two network reachability status values are equal.
211 ///
212 /// - parameter lhs: The left-hand side value to compare.
213 /// - parameter rhs: The right-hand side value to compare.
214 ///
215 /// - returns: `true` if the two values are equal, `false` otherwise.
216 public func ==(
217     lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
218     rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
219     -> Bool
220 {
221     switch (lhs, rhs) {
222     case (.unknown, .unknown):
223         return true
224     case (.notReachable, .notReachable):
225         return true
226     case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)):
227         return lhsConnectionType == rhsConnectionType
228     default:
229         return false
230     }
231 }
232
233 #endif