Skip to content

Instantly share code, notes, and snippets.

@greggjaskiewicz
Created February 13, 2020 13:19
Show Gist options
  • Save greggjaskiewicz/30c4d0e31ddbe7a20ae501e6fa00f793 to your computer and use it in GitHub Desktop.
Save greggjaskiewicz/30c4d0e31ddbe7a20ae501e6fa00f793 to your computer and use it in GitHub Desktop.
//
// ReachabilityUpdater.h
//
//
// Created by Gregg Jaskiewicz on 10/04/2018.
// Copyright © 2018 . All rights reserved.
//
#import <Foundation/Foundation.h>
typedef void (^ReachabilityUpdateCallback)(BOOL networkReachable);
@interface ReachabilityUpdater : NSObject
- (instancetype __nullable)init __attribute__((unavailable("You cannot create a ReachabilityUpdater instance through init - please initWithUpdateCallback:")));
- (instancetype _Nonnull)initWithUpdateCallback:(ReachabilityUpdateCallback __nonnull)callback NS_DESIGNATED_INITIALIZER;
@end
//
// ReachabilityUpdater.m
//
//
// Created by Gregg Jaskiewicz on 10/04/2018.
// Copyright © 2018 . All rights reserved.
//
#import "ReachabilityUpdater.h"
#import "Reachability.h"
@interface ReachabilityUpdater()
@property(nonatomic, copy) ReachabilityUpdateCallback callback;
@property(nonatomic, strong) Reachability *reachability;
@end
@implementation ReachabilityUpdater
- (instancetype)initWithUpdateCallback:(ReachabilityUpdateCallback)callback {
self = [super init];
if (self != nil) {
_callback = [callback copy];
self.reachability = [Reachability reachabilityForInternetConnection];
[self updateWithCurrentReachability:self.reachability.currentReachabilityStatus];
// subscribe to notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updated:) name:kReachabilityChangedNotification object:nil];
[self.reachability startNotifier];
}
return self;
}
- (void)dealloc {
NSLog(@"reachability updater going away");
}
- (void)updateWithCurrentReachability:(NetworkStatus)currentReachability {
BOOL wifiReachable = (currentReachability == ReachableViaWiFi);
BOOL wanReachable = (currentReachability == ReachableViaWWAN);
BOOL networkReachable = (wifiReachable == YES) || (wanReachable == YES);
self.callback(networkReachable);
}
- (void)updated:(NSNotification *)notification {
if ([notification.object isKindOfClass:[Reachability class]] == YES) {
Reachability *reachability = (Reachability *)notification.object;
NetworkStatus currentReachability = reachability.currentReachabilityStatus;
[self updateWithCurrentReachability:currentReachability];
} else {
NSLog(@"incorrect reachability?");
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment