How to return BOOL when checking internet connection in XCODE

前端 未结 4 1108
自闭症患者
自闭症患者 2021-01-23 03:52

I want to be able to check for internet connectivity when my View loads. To predetermine the contents of my view.

I have the following viewDidLoad method:



        
4条回答
  •  [愿得一人]
    2021-01-23 04:13

    What i do in My Projects :

    Create a custom class CheckInternet of type NSObject

    in CheckInternet.h file

    + (BOOL) isInternetConnectionAvailable;
    

    and in CheckInternet.m file

    + (BOOL) isInternetConnectionAvailable
    {
    Reachability *internet = [Reachability reachabilityWithHostName: @"www.google.com"];
    NetworkStatus netStatus = [internet currentReachabilityStatus];
    bool netConnection = false;
    switch (netStatus)
    {
        case NotReachable:
        {
            NSLog(@"Access Not Available");
            netConnection = false;
            break;
        }
        case ReachableViaWWAN:
        {
            netConnection = true;
            break;
        }
        case ReachableViaWiFi:
        {
            netConnection = true;
            break;
        }
    }
    return netConnection;
    }
    

    import this class to your desired class, Now you can access as

    in viewDidLoad or any other method where you want

    if ([CheckInternet isInternetConnectionAvailable])
    {
        // internet available
    }
    else
    {
        // no internet
     }
    

提交回复
热议问题