在我的 iOS 应用程序中,我需要使用 Reachability 来完成以下任务:
- 渲染视图控制器时,应用程序需要检查连接状态,并相应地显示连接图标图像(在线或离线)。
- 当用户停留在视图控制器上时,如果互联网连接状态发生变化,应用程序将收到更改通知,然后相应地执行一些任务。
我在我的应用程序中使用了由 Tony Million 生成的 Reachability 类,但是发生了一件奇怪的事情: 调用 startNotified 方法后,可达性状态变为 0(NotReachable)。
以下是我的代码:
BTLandingViewController.h
#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"
#import "Reachability.h"
@interface BTLandingViewController : UIViewController <UIAlertViewDelegate>
{
__weak IBOutlet UIImageView *internetIndicator;
MBProgressHUD *hud;
Reachability *reach;
UIAlertView *emptyRecordsAlert;
UIAlertView *syncReminderAlert;
}
@end
BTLandingViewController.m 中的部分代码
#import "BTLandingViewController.h"
@interface BTLandingViewController ()
@end
@implementation BTLandingViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Initialize reachability
reach = [Reachability reachabilityWithHostname:BTReachTestURL];
}
return self;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Register with reachability changed notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
NetworkStatus internetStatus = [reach currentReachabilityStatus]; // value = 1 or 2
***// PS: If there is connection, before [reach startNotifier], the internetStatus's value reflects the connection status (1 or 2)***
// Start notify reachability change
[reach startNotifier];
internetStatus = [reach currentReachabilityStatus]; // Value = 0;
***// PS: Even if there is connection, after [reach startNotifier], the internetStatus's value becomes 0***
}
谢谢您的帮助。