如何简单地测试与 IP 的本地 Wifi 连接,例如带有代码状态的 192.168.0.100?

How to simply test a local Wifi Connection to an IP, for example 192.168.0.100 with code status?

你知道我是否可以简单地测试是否有 WIFI 本地连接?例如,如果 url 192.168.0.100 是可达的。我尝试使用 Reachability 但没有成功。它告诉我它已连接,但事实并非如此。

我想先测试是否有本地 WIFI 连接,然后当我确定有连接时,启动该 Web 服务:

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

提前致谢。

NSURLConection 有很多委托方法。尝试以下操作之一:

- (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
    }
}

要测试互联网连接,您必须使用 Apple 的 Reachability。使用 ReachableViaWiFi 枚举检查可达性。

然后您需要对您的服务器执行 ping 操作。在您的 didReceiveResponse 方法中,您需要搜索成功到达您的服务器。

    - (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.
    }
}

已编辑

"I tried with the Reachability without success"

您是否碰巧忘记通知 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];