How To check if wifi option enabled or not

后端 未结 3 1444
天命终不由人
天命终不由人 2020-12-19 01:41

How to check if wifi option is enabled on the iPhone or not (but maybe iPhone not connected to one of the wifi net).

相关标签:
3条回答
  • 2020-12-19 01:45

    Found a great line of code for this. Add the Reachability class to your project and then you can do this:

    BOOL isConnectedProperly = ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == ReachableViaWiFi);
    
    0 讨论(0)
  • 2020-12-19 01:53
      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
      }       
    }
    

    When loginButtonTouched method is called we check that www.google.com is reachable or not. SCNetworkReachabilityFlags returns flags which helps us to understand the Status of internet connectivity. If isAvailable variable returns "true" then Host is Reachable means Wifi is reachable and Internet Connectivity is present.

    0 讨论(0)
  • 2020-12-19 02:06

    For this you need to import reachability classes in your project.

    After then:-

    #import "Reachability.h"
    

    In you view DidLoad write:-

    - (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;
    }
    }
    
    0 讨论(0)
提交回复
热议问题