How to simply test a local Wifi Connection to an I

2019-07-25 09:32发布

问题:

Do you know if I can simply test if there is a WIFI local connection ? For example if the url 192.168.0.100 is reachable. I tried with the Reachability without success. It tells me that it is connected, but it is not true.

I would like first to test if there is a local WIFI connection, and then when I am sure there is a connection, launch that Web Service :

- (void)callWebService:(NSString *)url withBytes:(NSString *) bytes //GET
{
        NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
        NSString *url_string = [bytes stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [request setURL:[NSURL URLWithString:[url stringByAppendingString: url_string]]];
        [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
        [request setTimeoutInterval:timeOut];
        NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; //try NSURLSession
        [connection start];
}

Thanks in advance.

回答1:

NSURLConection have many delegate methods. try one of the following:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self.download_connection cancel]; // optional depend on what you want to achieve.
    self.download_connection = nil; // optional

    DDLogVerbose(@"Connection Failed with error: %@", [error description]);
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    NSInteger state = [httpResponse statusCode];

    if (state >= 400 && state < 600)
    {
        // something wrong happen.
        [self.download_connection cancel]; // optional
        self.download_connection = nil; // optional
    }
}


回答2:

To test for internet connection you must employ Apple's Reachability. Check for reachability with the ReachableViaWiFi enumeration.

Then you will need to do a ping of your server. In your didReceiveResponse method you need to search for a successful reach of your server.

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    NSInteger status = [httpResponse statusCode];

    if (status >= 200 && status <300)
    {
        // You are able to reach the server. Do something.
    }
}

EDITED

"I tried with the Reachability without success"

Did you happen to forget to notify reachability to startNotifier?

Reachability *reachability = [Reachability reachabilityWithHostname:@"www.google.com"];

reachability.reachableBlock = ^(Reachability *reachability) {
    NSLog(@"Network is reachable.");
};

reachability.unreachableBlock = ^(Reachability *reachability) {
    NSLog(@"Network is unreachable.");
};

// Start Monitoring
[reachability startNotifier];