Internet连接(Rechability)不起作用

时间:2015-08-06 04:15:57

标签: ios objective-c reachability

我使用以下代码进行互联网连接但无法正常工作(当wifi或互联网更改时,reachabilityChanged不会调用)

//Internet.m : 
...
@interface Internet ()
@property (nonatomic) Reachability *Wifi;
@end

@implementation Internet

-(void)checkNetwork
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    self.Wifi = [Reachability reachabilityForLocalWiFi];
    [self.Wifi startNotifier];
}

- (void) reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    if (curReach == self.Wifi)
    {
        NetworkStatus netStatus = [curReach currentReachabilityStatus];
        if(netStatus == NotReachable)
        {
            NSString *status=@"NO";
        }//if
        else if(netStatus == ReachableViaWiFi)
        {
            NSString *status=@"Yes";
        }//else
    }//if
}//reachabilityChanged

//ViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    [self performSelectorInBackground:@selector(callInternet) withObject:nil];
}//load

-(void)callInternet
{
    inter=[[Internet alloc]init];//inter is instance variable
    [inter checkNetwork];
}//callInternet

1 个答案:

答案 0 :(得分:0)

@sajidZare,

Appdelegate.h 文件

//Check Internet Connection
.//Define method for that
-(BOOL)checkInternetConnection;
Appdelegate.m 文件

中的

 //Check Internet Plugin
    #include<unistd.h>
    #include<netdb.h>

    #pragma mark Check Internet connection
    -(BOOL)checkInternetConnection {

        char *hostname;
        struct hostent *hostinfo;
        hostname = "google.com";
        hostinfo = gethostbyname (hostname);
        if (hostinfo == NULL)
        {
            NSLog(@"-> no connection!\n");
            return NO;
        }
        else{
            NSLog(@"-> connection established!\n");
            return YES;
        }

    }

//这是最佳解决方案,尝试一下,可能对您有所帮助。

另一种解决方案 你的.h文件中的

    #import "Reachability.h"            // internet Rechability
    //---rechability methods---//
    @property (nonatomic) Reachability *internetReachability;
-(void)checkInternet;
你的.m档案

-(void)checkInternet
{
    self.internetReachability = [Reachability reachabilityForInternetConnection];
    if (self.internetReachability.currentReachabilityStatus==NotReachable)
    {
        NSLog(@"internet is not available..");
        [self internetAlertView];
    }


    else
        {
            NSLog(@"internet Available..");
*//Here you can do whatever you want to do//*
            [self BTN_Spark:self];
        }
        [self.internetReachability startNotifier];
    }


    -(void)internetAlertView
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Please check the internet connection!!!" delegate:self cancelButtonTitle:@"OK"  otherButtonTitles:nil];
        [alertView show];
    }