如何检查iPhone上是否启用了wifi选项(但可能iPhone未连接到其中一个wifi网络)。
答案 0 :(得分:12)
为此,您需要在项目中导入可达性类。
之后: -
#import "Reachability.h"
在你看来DidLoad写道: -
- (void)viewDidLoad {
Reachability *internetReach = [[Reachability reachabilityForInternetConnection] retain];
[internetReach startNotifer];
Reachability *wifiReach = [[Reachability reachabilityForLocalWiFi] retain];
[wifiReach startNotifer];
NetworkStatus netStatus1 = [internetReach currentReachabilityStatus];
NetworkStatus netStatus2 = [wifiReach currentReachabilityStatus];
if(netStatus1 == NotReachable && netStatus2 == NotReachable)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"This feature requires an internet connection." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{//wifi connection available;
}
}
答案 1 :(得分:4)
为此找到了很多代码。 将Reachability类添加到项目中,然后您可以执行此操作:
BOOL isConnectedProperly = ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == ReachableViaWiFi);
答案 2 :(得分:1)
First import Reachability files into your project.
-(void)loginButtonTouched
{
bool success = false;
const char *host_name = [@"www.google.com"
cStringUsingEncoding:NSASCIIStringEncoding];
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName
(NULL, host_name);
SCNetworkReachabilityFlags flags;
success = SCNetworkReachabilityGetFlags(reachability, &flags);
bool isAvailable = success && (flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired);
if (isAvailable)
{
NSLog(@"Host is reachable: %d", flags);
// Perform Action if Wifi is reachable and Internet Connectivity is present
}
else
{
NSLog(@"Host is unreachable");
// Perform Action if Wifi is reachable and Internet Connectivity is not present
}
}
调用loginButtonTouched
方法后,我们会检查www.google.com是否可以访问。
SCNetworkReachabilityFlags
返回标志,帮助我们了解互联网连接的状态。
如果isAvailable
变量返回“true”,则Host为
可访问意味着可以访问Wifi并且存在Internet连接。