在我的初始视图控制器的viewDidLoad中,我检查互联网连接,如果可用,则开始一些下载过程。
如果没有任何连接(WiFi 或移动)或互联网可用 - 一切正常。但是,如果设备在没有互联网的情况下连接到 WiFi,应用程序会冻结。
if ([self isInternetAvail]) {
[[Download sharedDownload] startUpdateProcessWithIndicatorInViewController:self];
}
这是功能:
- (BOOL)isInternetAvail
{
NSString *hostName = @"google.com";
Reachability *hostReach = [Reachability reachabilityWithHostName:hostName];
NetworkStatus netStatus = [hostReach currentReachabilityStatus];
if (netStatus == NotReachable) {
return NO;
} else {
return YES;
}
}
应用程序在此行冻结:
NetworkStatus netStatus = [hostReach currentReachabilityStatus];
使用更正确的方法来检查互联网连接,NSNotificationCenter
但在这种情况下:
1)在didFinishLaunchingWithOptions:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(networkStateChanged:)
name:kReachabilityChangedNotification
object:nil];
hostReach = [Reachability reachabilityWithHostName:@"www.google.com"];
[hostReach startNotifier];
[self updateInternetAvailWithReachability: hostReach];
附加方法:
- (void)updateInternetAvailWithReachability: (Reachability *)curReach
{
netStatus = [curReach currentReachabilityStatus];
}
- (void)networkStateChanged:(NSNotification *)notification
{
Reachability *curReach = [notification object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
[self updateInternetAvailWithReachability:curReach];
}
2)在我的初始视图控制器的viewDidLoad中:
AppDelegate *d = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if (!d.netStatus == NotReachable) {
[[Download sharedDownload] startUpdateProcessWithIndicatorInViewController:self];
}
在这一步我得到NotReachable并且无法开始下载
3) NSNotificationCenter 告诉我“互联网可用”
我需要一些建议如何准备这个。