Blame view

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