【发布时间】:2011-12-28 19:22:47
【问题描述】:
我的 iPhone 应用程序需要互联网才能运行。
是否应该在每次执行 Internet 功能时检查连接? 或者我应该使用我的 appDelegate 来监听来自可达性类之类的消息,以确定连接是否丢失并警告用户?
什么更好?
这是我迄今为止在我的应用委托中所做的:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
reachability = [[Reachability reachabilityWithHostName:[NSString stringWithFormat:@"http://%@/iSql/" ,[[NSUserDefaults standardUserDefaults] stringForKey:@"serviceIPAddress"]]] retain];
[reachability startNotifier];
return YES;
}
- (void)reachabilityChanged:(NSNotification *)note {
NetworkStatus ns = [(Reachability *)[note object] currentReachabilityStatus];
if (ns == NotReachable) {
if (![networkAlert isVisible]) {
if ([self networkAlert] == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"\n\nNo Internet Connection" message:@"You require an internet connection to retrieve data from the server." delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
[self setNetworkAlert:alert];
[alert release];
}
[networkAlert show];
}
} else {
if ([self networkAlert] != nil) {
[networkAlert dismissWithClickedButtonIndex:0 animated:YES];
}
}
}
【问题讨论】:
标签: iphone objective-c networking reachability