我使用 Apples Reachability 类,如果我把它放在主线程上它就可以工作(不好的方法)。如果我将其移至单独的线程,则永远不会调用通知。
在didFinishLaunchingWithOptions
我调用以下内容:
[NSThread detachNewThreadSelector:@selector(checkConnection) toTarget:self withObject: nil];
checkConnection 如下所示:
-(void)checkConnection {
//Test for Internet Connection
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
Reachability *r = [[Reachability reachabilityWithHostName:@"appspot.com"] retain];
[r updateReachability:appDelegate.reachability];
[r startNotifier];
[pool release];
}
和reachabilityChanged 看起来像这样:
- (void)reachabilityChanged:(NSNotification *)note {
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
[self updateReachability: curReach];
}
最后 updateReachability 看起来像这样:
- (void)updateReachability:(Reachability *)curReach {
NetworkStatus internetStatus = [curReach currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
NSLog(@"No net");
} else {
NSLog(@"Lots of net");
}}
希望你们能帮助我理解为什么reachabilityChanged
永远不会被调用。
干杯...