我正在尝试使用 Xcode 4.4 中的可达性来提醒用户,如果他/她没有连接到互联网。我的初始视图控制器有一个加载表格的按钮(从 plist 在线填充)。我遵循了 Stack Overflow 中的一些示例,但无法使其正常工作。这是我的 .h 文件的片段:
#import <UIKit/UIKit.h>
#import "Reachability.h"
@interface MainPageViewController : UIViewController
{
Reachability *internetReachable;
Reachability *hostReachable;
}
-(void) checkNetworkStatus: (NSNotification *)notice;
@property BOOL internetActive;
@property BOOL hostActive;
@end
这是我的 .m 文件:
#import "MainPageViewController.h"
#import "Reachability.h"
@implementation MainPageViewController
@synthesize internetActive;
@synthesize hostActive;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void) viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] addObserver: self selector:
@selector(checkNetworkStatus:) name: kReachabilityChangedNotification object: nil];
internetReachable = [Reachability reachabilityForInternetConnection];
[internetReachable startNotifier];
hostReachable = [Reachability reachabilityWithHostname: @"sites.google.com"];
[hostReachable startNotifier];
}
- (void) checkNetworkStatus:(NSNotification *)notice
{
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
if((internetStatus == NotReachable) && (hostStatus == NotReachable))
{
UIAlertView *internetAlert = [[UIAlertView alloc] initWithTitle:@"Network Error!"
message: @"You are not connected to the internet!" delegate: self
cancelButtonTitle: @"Ok" otherButtonTitles: nil];
[internetAlert show];
self.internetActive = NO;
self.hostActive = NO;
}
}
-(void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver: self];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
@end
由于我使用的是按钮,在导航到下一页之前是否应该使用 IBAction 来检查互联网?