有很多关于使用 Apple 的可达性示例的信息,而且很多都是相互矛盾的。我试图找出我在下面正确使用它(Reachability 2.0)。我的应用程序用例是这样的:如果可以通过任何方式(wifi、LAN、Edge、3G 等)获得 Internet 连接,则在各种视图上都可以看到 UIButton(“查看更多”)。如果没有连接,则该按钮不可见。“查看更多”部分对应用程序来说并不重要,它只是一个附加功能。随着连接的建立或丢失,“查看更多”在应用程序生命周期中的任何时候都可能可见或不可见。这就是我的做法 - 这是正确的和/或有更好的方法吗?
任何帮助是极大的赞赏!lq
// AppDelegate.h
#import "RootViewController.h"
@class Reachability;
@interface AppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UINavigationController *navigationController;
RootViewController *rootViewController;
Reachability* hostReach;
// NOT USED: Reachability* internetReach;
// NOT USED: Reachability* wifiReach;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@property (nonatomic, retain) IBOutlet RootViewController *rootViewController;
@end
// AppDelegate.m
#import "AppDelegate.h"
#import "Reachability.h"
#define kHostName @"www.somewebsite.com"
@implementation AppDelegate
@synthesize window;
@synthesize navigationController;
@synthesize rootViewController;
- (void) updateInterfaceWithReachability: (Reachability*) curReach {
if(curReach == hostReach) {
NetworkStatus netStatus = [curReach currentReachabilityStatus];
BOOL connectionRequired = [curReach connectionRequired];
// Set a Reachability BOOL value flag in rootViewController
// to be referenced when opening various views
if ((netStatus != ReachableViaWiFi) && (netStatus != ReachableViaWWAN)) {
rootViewController.bConnection = (BOOL *)0;
} else {
rootViewController.bConnection = (BOOL *)1;
}
}
}
- (void) reachabilityChanged: (NSNotification* )note {
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
[self updateInterfaceWithReachability: curReach];
}
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// NOTE: #DEFINE in Reachability.h:
// #define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification"
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
hostReach = [[Reachability reachabilityWithHostName: kHostName] retain];
[hostReach startNotifer];
[self updateInterfaceWithReachability: hostReach];
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}
- (void)dealloc {
[navigationController release];
[rootViewController release];
[window release];
[super dealloc];
}
@end