如何简单地测试本地Wifi连接到IP,例如192.168.0.100的代码状态?
您是否知道我是否可以简单地测试是否存在WIFI本地连接?例如,如果网址192.168.0.100可到达。我试图与可达性没有成功。它告诉我它已连接,但事实并非如此。如何简单地测试本地Wifi连接到IP,例如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];
}
在此先感谢。
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
}
}
为了测试你必须使用苹果的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.
}
}
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];
谢谢,我相信有一种异步方法。可达性不是检查本地状态代码的好方法200 – Claudio
是的可达性不会告诉你,如果你的回应是200。它只是一个实用工具类,用于确定网络连接,以便您可以拨打电话获得响应。 –
192.168.0.100不是URL。地址是可达的,但没有HTTP服务监听是完全可能的。 –
我知道地址是返回200,如果我把一些不存在,像192.168.0.101,返回我404。但是,如果我使用可达性,它每次返回我YES。所以我想知道是否有办法拥有这个状态码?我试图用一个异步NSURL连接,它的工作原理,但问题是,它不执行connectionDidFinishLoading => http://stackoverflow.com/questions/42490047/connectiondidfinishloading-not-called-with-the-use-of -nsurlconnection-sendasyn/42490402?noredirect = 1#comment72129076_42490402 – Claudio