如何简单地测试的代码状态的本地WiFi连接到IP,例如192.168.0.100?(How to s

2019-09-28 05:59发布

你知道,如果我可以简单地测试是否有WIFI本地连接? 例如,如果网址192.168.0.100可达。 我试图与没有成功的可达性。 它告诉我,它是连接的,但事实并非如此。

我想首先要测试是否有本地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];
}

提前致谢。

Answer 1:

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


Answer 2:

为了测试你必须使用苹果的互联网连接可达性 。 检查与可达性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.
    }
}

EDITED

“我试图与可达性没有成功”

你碰巧忘了通知可达性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];


文章来源: How to simply test a local Wifi Connection to an IP, for example 192.168.0.100 with code status?