如何在 iOS 中检查互联网是否处于活动状态(同时检查网络可用性和网页可访问性)?
How to check whether internet is active (checking both network availability & webpage accessibility) in iOS?
我目前在一个 iOS 项目中工作,我需要检查我的 phone 是否连接到互联网(手机 data/wifi)。我正在使用仅检查网络连接可用性的可达性 class,但假设我的 phone 中没有余额。在那种情况下,我将无法访问互联网,但仍然可访问性显示我可以通过移动网络访问互联网,因为数据连接已打开,尽管我无法访问该页面。
我该如何解决这个问题?
另一个例子是,如果您未正确连接到 Wifi 网络 - 您的 phone 连接良好,但无权访问 Internet 上的任何页面。
在这种情况下,唯一的检测方法是尝试将 Web 请求发送到可靠的站点(比如 www.google.com)。如果您对该源的请求在设定的时间(比如五秒)后超时,那么您可以放心地断定 phone 存在连接问题。
您可以检查互联网连接
NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
//Manual timeout of 20 seconds
[NSThread sleepForTimeInterval: 20];
if (data)
NSLog(@"Device is connected to the Internet");
else
NSLog(@"Device is not connected to the Internet");
参考这个link
您可以使用 connection:didReceiveResponse:
检查
NSString *urlString=@"yourUrl";
NSURL *url=[NSURL URLWithString:urlString];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
NSURLConnection *connection=[NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%@",response);
[connection cancel];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int code = (int)[httpResponse statusCode];
if (code == 200) {
NSLog(@"File exists");
}
else if(code == 404)
{
NSLog(@"File not exist");
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"File not exist");
}
我目前在一个 iOS 项目中工作,我需要检查我的 phone 是否连接到互联网(手机 data/wifi)。我正在使用仅检查网络连接可用性的可达性 class,但假设我的 phone 中没有余额。在那种情况下,我将无法访问互联网,但仍然可访问性显示我可以通过移动网络访问互联网,因为数据连接已打开,尽管我无法访问该页面。
我该如何解决这个问题?
另一个例子是,如果您未正确连接到 Wifi 网络 - 您的 phone 连接良好,但无权访问 Internet 上的任何页面。
在这种情况下,唯一的检测方法是尝试将 Web 请求发送到可靠的站点(比如 www.google.com)。如果您对该源的请求在设定的时间(比如五秒)后超时,那么您可以放心地断定 phone 存在连接问题。
您可以检查互联网连接
NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
//Manual timeout of 20 seconds
[NSThread sleepForTimeInterval: 20];
if (data)
NSLog(@"Device is connected to the Internet");
else
NSLog(@"Device is not connected to the Internet");
参考这个link
您可以使用 connection:didReceiveResponse:
检查 NSString *urlString=@"yourUrl";
NSURL *url=[NSURL URLWithString:urlString];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
NSURLConnection *connection=[NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%@",response);
[connection cancel];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int code = (int)[httpResponse statusCode];
if (code == 200) {
NSLog(@"File exists");
}
else if(code == 404)
{
NSLog(@"File not exist");
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"File not exist");
}