Sascha Simon Sascha Simon - 16 days ago 10
Objective-C Question

Detect hardware / network adaptor changes

Is it possible to detect hardware changes? I'm looking for an update notification that is sent when the network adaptors are changed (i.e. when the user undocks his MacBook).

I already googled, but couldn't find anything.

A O A O
Answer

I have used AFNetworking, and found it to be the easiest to use for this (listening for adapter changes)

#import <AFNetworking/AFNetworkReachabilityManager.h>

- (instancetype)init 
{
   self = [super init];
   if( self )
   {
      [[AFNetworkReachabilityManager sharedManager] startMonitoring];
      [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(reachabilityChanged:)
                                                name:AFNetworkingReachabilityDidChangeNotification
                                              object:nil];
   }
   return self;
}


-(void) dealloc
{
   [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:AFNetworkingReachabilityDidChangeNotification
                                                 object:nil];
}

and then implement the handler:

- (void)reachabilityChanged:(NSNotification *)notification
{
   NSNumber *s = notification.userInfo[AFNetworkingReachabilityNotificationStatusItem];
   AFNetworkReachabilityStatus status = [s integerValue];

   //Check value of status here
}

Here is the header where you can see the constants used for status: https://github.com/AFNetworking/AFNetworking/blob/4fb051898c60051d207ca0c24435766fdf140e34/AFNetworking/AFNetworkReachabilityManager.h

I have also used SCReachability

   #import <SystemConfiguration/SystemConfiguration.h>

   BOOL networkAvailable = NO;
   const char *hostName = [NEVER_TRANSLATE(@"google.com") cStringUsingEncoding:NSASCIIStringEncoding];
   SCNetworkReachabilityFlags flags = 0;
   SCNetworkReachabilityRef target = SCNetworkReachabilityCreateWithName(NULL, hostName);

   if (SCNetworkReachabilityGetFlags(target, &flags))
   {
      if (flags == kSCNetworkFlagsReachable)
      {
         networkAvailable = YES;
      }
   }

Though I used this to detect network availability at a specific time, instead of registering as a listener, so not sure if this will do what you want