I'm using the following code to detect when a user has connectivity to the internet. If there's no connectivity, add a subview to show that. If the user regains connectivity, remove the view.
Adding the view works just fine, however removing it isn't working. Anybody know why? (Yes, I have double checked that removeNetworkIndicator is getting called)
- (void)testInternetConnection
{
__weak typeof(self) weakSelf = self;
internetReachable = [Reachability reachabilityWithHostname:@"google.com"];
// Internet is reachable
internetReachable.reachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf removeNetworkIndicator];
});
};
// Internet is not reachable
internetReachable.unreachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf addNetworkIndicator];
});
};
[internetReachable startNotifier];
}
- (void)addNetworkIndicator {
NetworkIndicatorViewController *networkIndicatorView = [[NetworkIndicatorViewController alloc] initWithNibName:@"NetworkIndicatorViewController" bundle:nil]; //creat an instance of your custom view
networkIndicatorView.activityIndicator.hidden = YES;
networkIndicatorView.view.tag = 400;
[self.view addSubview:networkIndicatorView.view];
}
- (void)removeNetworkIndicator {
UIView *networkIndicator = (UIView *)[self.view viewWithTag:400];
NSLog(@"networkindicator: %@",networkIndicator);
networkIndicator.hidden = YES;
[networkIndicator removeFromSuperview];
}
Sidenote: the NSLog networkindicator is logging (null) but I don't understand why...
It's not immediately clear to me why your current code isn't working, but in the meantime, you can do this:
- (void)removeNetworkIndicator {
for(UIView *subview in self.view.subviews) {
if ([subview isKindOfClass:[NetworkIndicatorViewController class]]) {
[subview removeFromSuperview];
}
}
}
Also... make sure you're using a UIView
subclass and not a UIViewController
subclass.
create a property for the view in your view controller:
@property (nonatomic, strong) NetworkIndicatorViewController *networkIndicatorView
and then simply use this to show:
[self.view addSubview:self.networkIndicatorView.view];
and this to hide:
[self.networkIndicatorView.view removeFromSuperview];
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.