AFNetworkReachabilityManager.m 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // AFNetworkReachabilityManager.m
  2. // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. #import "AFNetworkReachabilityManager.h"
  22. #if !TARGET_OS_WATCH
  23. #import <netinet/in.h>
  24. #import <netinet6/in6.h>
  25. #import <arpa/inet.h>
  26. #import <ifaddrs.h>
  27. #import <netdb.h>
  28. NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
  29. NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
  30. typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
  31. typedef AFNetworkReachabilityManager * (^AFNetworkReachabilityStatusCallback)(AFNetworkReachabilityStatus status);
  32. NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
  33. switch (status) {
  34. case AFNetworkReachabilityStatusNotReachable:
  35. return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
  36. case AFNetworkReachabilityStatusReachableViaWWAN:
  37. return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
  38. case AFNetworkReachabilityStatusReachableViaWiFi:
  39. return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
  40. case AFNetworkReachabilityStatusUnknown:
  41. default:
  42. return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
  43. }
  44. }
  45. static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
  46. BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
  47. BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
  48. BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
  49. BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
  50. BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
  51. AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
  52. if (isNetworkReachable == NO) {
  53. status = AFNetworkReachabilityStatusNotReachable;
  54. }
  55. #if TARGET_OS_IPHONE
  56. else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
  57. status = AFNetworkReachabilityStatusReachableViaWWAN;
  58. }
  59. #endif
  60. else {
  61. status = AFNetworkReachabilityStatusReachableViaWiFi;
  62. }
  63. return status;
  64. }
  65. /**
  66. * Queue a status change notification for the main thread.
  67. *
  68. * This is done to ensure that the notifications are received in the same order
  69. * as they are sent. If notifications are sent directly, it is possible that
  70. * a queued notification (for an earlier status condition) is processed after
  71. * the later update, resulting in the listener being left in the wrong state.
  72. */
  73. static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusCallback block) {
  74. AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
  75. dispatch_async(dispatch_get_main_queue(), ^{
  76. AFNetworkReachabilityManager *manager = nil;
  77. if (block) {
  78. manager = block(status);
  79. }
  80. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  81. NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
  82. [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:manager userInfo:userInfo];
  83. });
  84. }
  85. static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
  86. AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusCallback)info);
  87. }
  88. static const void * AFNetworkReachabilityRetainCallback(const void *info) {
  89. return Block_copy(info);
  90. }
  91. static void AFNetworkReachabilityReleaseCallback(const void *info) {
  92. if (info) {
  93. Block_release(info);
  94. }
  95. }
  96. @interface AFNetworkReachabilityManager ()
  97. @property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
  98. @property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
  99. @property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
  100. @end
  101. @implementation AFNetworkReachabilityManager
  102. + (instancetype)sharedManager {
  103. static AFNetworkReachabilityManager *_sharedManager = nil;
  104. static dispatch_once_t onceToken;
  105. dispatch_once(&onceToken, ^{
  106. _sharedManager = [self manager];
  107. });
  108. return _sharedManager;
  109. }
  110. + (instancetype)managerForDomain:(NSString *)domain {
  111. SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
  112. AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
  113. CFRelease(reachability);
  114. return manager;
  115. }
  116. + (instancetype)managerForAddress:(const void *)address {
  117. SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
  118. AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
  119. CFRelease(reachability);
  120. return manager;
  121. }
  122. + (instancetype)manager
  123. {
  124. #if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
  125. struct sockaddr_in6 address;
  126. bzero(&address, sizeof(address));
  127. address.sin6_len = sizeof(address);
  128. address.sin6_family = AF_INET6;
  129. #else
  130. struct sockaddr_in address;
  131. bzero(&address, sizeof(address));
  132. address.sin_len = sizeof(address);
  133. address.sin_family = AF_INET;
  134. #endif
  135. return [self managerForAddress:&address];
  136. }
  137. - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
  138. self = [super init];
  139. if (!self) {
  140. return nil;
  141. }
  142. _networkReachability = CFRetain(reachability);
  143. self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
  144. return self;
  145. }
  146. - (instancetype)init
  147. {
  148. @throw [NSException exceptionWithName:NSGenericException
  149. reason:@"`-init` unavailable. Use `-initWithReachability:` instead"
  150. userInfo:nil];
  151. return nil;
  152. }
  153. - (void)dealloc {
  154. [self stopMonitoring];
  155. if (_networkReachability != NULL) {
  156. CFRelease(_networkReachability);
  157. }
  158. }
  159. #pragma mark -
  160. - (BOOL)isReachable {
  161. return [self isReachableViaWWAN] || [self isReachableViaWiFi];
  162. }
  163. - (BOOL)isReachableViaWWAN {
  164. return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
  165. }
  166. - (BOOL)isReachableViaWiFi {
  167. return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
  168. }
  169. #pragma mark -
  170. - (void)startMonitoring {
  171. [self stopMonitoring];
  172. if (!self.networkReachability) {
  173. return;
  174. }
  175. __weak __typeof(self)weakSelf = self;
  176. AFNetworkReachabilityStatusCallback callback = ^(AFNetworkReachabilityStatus status) {
  177. __strong __typeof(weakSelf)strongSelf = weakSelf;
  178. strongSelf.networkReachabilityStatus = status;
  179. if (strongSelf.networkReachabilityStatusBlock) {
  180. strongSelf.networkReachabilityStatusBlock(status);
  181. }
  182. return strongSelf;
  183. };
  184. SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
  185. SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
  186. SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
  187. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),^{
  188. SCNetworkReachabilityFlags flags;
  189. if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) {
  190. AFPostReachabilityStatusChange(flags, callback);
  191. }
  192. });
  193. }
  194. - (void)stopMonitoring {
  195. if (!self.networkReachability) {
  196. return;
  197. }
  198. SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
  199. }
  200. #pragma mark -
  201. - (NSString *)localizedNetworkReachabilityStatusString {
  202. return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
  203. }
  204. #pragma mark -
  205. - (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
  206. self.networkReachabilityStatusBlock = block;
  207. }
  208. #pragma mark - NSKeyValueObserving
  209. + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
  210. if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
  211. return [NSSet setWithObject:@"networkReachabilityStatus"];
  212. }
  213. return [super keyPathsForValuesAffectingValueForKey:key];
  214. }
  215. @end
  216. #endif