ASIHTTPRequest Reachability How to

2019-04-09 18:49发布

问题:

As much as I like ASIHTTPRequest, it isn't documented anywhere how to use the modified the Reachability class, and I couldnt find it on stackoverflow, or any sample projects either.

Currently im at this point:

Reachability *reach = [Reachability reachabilityWithHostName:@"http://google.com"];
[reach startNotifier];

if ([reach isReachable]) {
    NSLog(@"connection");
}else{
    NSLog(@"no connection");
}

Which doesn't seem to work.

回答1:

You need to set up a notification handler for this:

Reachability *reach = [Reachability reachabilityWithHostName:@"http://google.com"];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(reachabilityChanged:)
                                             name:kReachabilityChangedNotification
                                           object:nil];
[reach startNotifier];

Then, implement the handler like so:

- (void) reachabilityChanged:(Reachability *) reach {
    if ([reach isReachable]) {
       NSLog(@"connection");
    } else{
       NSLog(@"no connection");
    }
}

Also, when you don't need to know when things change, remove yourself as an observer:

[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];



回答2:

- (void) reachabilityChanged:(NSNotification *)notification
{
    Reachability *localReachability = [notification object]; 


    if ([localReachability isReachable])

    {
        NSLog(@"connection");
    } else{
        NSLog(@"no connection");
    }

}

, Please make these changes then code gonna work like a charm :)