Skip to content

Instantly share code, notes, and snippets.

@advantis
Created May 19, 2013 16:07
Show Gist options
  • Save advantis/5608103 to your computer and use it in GitHub Desktop.
Save advantis/5608103 to your computer and use it in GitHub Desktop.
Naive Reachability replacement
//
// Copyright © 2013 Advantis
//
#import <SystemConfiguration/SystemConfiguration.h>
typedef void (^ADVReachabilityHandler)(SCNetworkReachabilityFlags flags);
@interface ADVReachability : NSObject
@property (readonly, nonatomic) SCNetworkReachabilityFlags flags;
- (instancetype) initWithHandler:(ADVReachabilityHandler)handler;
@end
//
// Copyright © 2013 Advantis
//
#import "ADVReachability.h"
@interface ADVReachability ()
@property (strong, nonatomic) ADVReachabilityHandler handler;
- (void) reachabilityDidChange:(SCNetworkReachabilityFlags)flags;
@end
static void ADVReachabilityCallback(__unused SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info)
{
ADVReachability *self = (__bridge id) info;
@autoreleasepool
{
[self reachabilityDidChange:flags];
}
}
@implementation ADVReachability
{
SCNetworkReachabilityRef _reachability;
}
#pragma mark - ADVReachability
- (instancetype) initWithHandler:(ADVReachabilityHandler)handler
{
if ((self = [super init]))
{
struct sockaddr address = {sizeof address, AF_INET};
_reachability = SCNetworkReachabilityCreateWithAddress(NULL, &address);
if (handler)
{
_handler = handler;
SCNetworkReachabilityContext context = {0, (__bridge void *) self};
SCNetworkReachabilitySetCallback(_reachability, ADVReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop(_reachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}
}
return self;
}
- (SCNetworkReachabilityFlags) flags
{
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityGetFlags(_reachability, &flags);
return flags;
}
- (void) reachabilityDidChange:(SCNetworkReachabilityFlags)flags
{
_handler(flags);
}
#pragma mark - NSObject
- (void) dealloc
{
SCNetworkReachabilityUnscheduleFromRunLoop(_reachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFRelease(_reachability);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment