简体   繁体   中英

ASIHTTPRequest Reachability How to

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.

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];

- (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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM