Reachability not working as expected

前端 未结 6 908
不思量自难忘°
不思量自难忘° 2021-02-19 02:53

Downloaded Reachability from Apple, using this method to check for an active connection:

-(BOOL)isReachable{

    Reachability *r = [Reachability reachabilityWit         


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 03:39

    If you are trying to see if the device can reach the internet in general you should probably use reachabilityForInternetConnection instead of reachabilityWithHostName:. Also, both of these calls will take a little bit of time to start up (it will still be in the milliseconds but longer than the time it takes to reach the if condition on the next line.) Here's an example of a singleton class that uses reachability.

    static NetworkManager* sharedInstance = nil;
    
    @interface NetworkManager()
    @property (nonatomic, strong) Reachability* reachability;
    @end
    
    @implementation NetworkManager
    @synthesize reachability;
    
    + (NetworkManager*)sharedInstance
    {
        @synchronized(self) {
            if (sharedInstance == nil) {
                sharedInstance = [[NetworkManager alloc] init];
            }
        }
        return sharedInstance;
    }
    
    - (id)init
    {
        reachability = [WYReachability reachabilityForInternetConnection];
    }
    
    - (BOOL)isNetworkReachable
    {
        return ([self.reachability currentReachabilityStatus] != NotReachable);
    }
    @end
    

    To check for the network reachable in other classes you can use.

    [[NetworkManager sharedInstance] isNetworkReachable];
    

提交回复
热议问题