I need my app to constantly listen for reachability
changes and update my views according to the network status
, i am thinking about using the notificationcenter
, and let all my views listen for changes, but i have no idea how to implement this.
I know how to use the notificationcenter
and Reachability
but i can't seem to find a place to implement the Reachability check
.
Where should i check for network changes, and notify the other ViewControllers
?
I don't think AppDelegate
is the right place, and if i put the Reachability
check in a ViewController the network checking is only being performed as long as the ViewController
is "active".
Create a "singleton" Reachability
and initialize it at app launch.
Let the singleton check for reachability periodically, eg with NSTimer
. It can then notify any other active views that registered with NSNotificationCenter
.
// AppDelegate.m:
@property (nonatomic, strong) Reachability *reachability;
// in applicationDidFinishLaunching...
self.reachability = [[Reachability alloc] init];
and
// Reachability.m
-(id)init {
self = [super init];
if (self) {
[self setupTheTimer];
}
return self;
}
I would create a singleton NSObject
class that handles all the network checks.
Name it like NetworkChecker.
Create a delegate for the callback, like NetworkCheckerDelegate
with a method like:
@protocol NetworkCheckerDelegate <NSObject>
-(void)networkStatusUpdated:(NSInteger)networkStatus;
@end
@interface NetworkChecker : NSObject
{
id<NetworkCheckerDelegate> networkDelegate;
}
Add a method to start the network checking and add a delegate to it like:
+(void)updateNetworkWithDelegate:(id<NetworkCheckerDelegate>)delegate
{
networkDelegate = delegate;
//Set timer to do Reachability checks
}
-(void)timerIsCompleted
{
//Do Reachability check
if( newNetworkState != oldNetworkState ){
[networkDelegate networkStatusUpdated:newNetworkState];
}
}
Then in each ViewController
you need it you can do (do this in viewDidLoad):
[NetworkChecker updateNetworkWithDelegate:self];
And implement the following to do something after the network status changed:
-(void)networkStatusUpdated:(NSInteger)networkStatus
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.