zoukankan      html  css  js  c++  java
  • iOS 判断有无网络连接

    众所周知,我们在开发APP时,涉及网络连接的时候,都会想着提前判断一下当前的网络连接状态,如果没有网络,就不再请求url,省去不必要的步骤,所以,这个如何判断?其实很简单。


    前提:工程添加:SystemConfiguration.framework framework


    然后在需要判断的类中包含头文件:

    1. #import "Reachability.h"  


    【如果你使用的ASIHTTPRequest类库,那么直接import Reachbility.h就可以了,ASIHTTP类库里包含Reachbility.h和.m】



    下面是我写的一个方法:

    1. -(BOOL) isConnectionAvailable{  
    2.   
    3.     BOOL isExistenceNetwork = YES;  
    4.     Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];  
    5.     switch ([reach currentReachabilityStatus]) {  
    6.         case NotReachable:  
    7.             isExistenceNetwork = NO;  
    8.             //NSLog(@"notReachable");  
    9.             break;  
    10.         case ReachableViaWiFi:  
    11.             isExistenceNetwork = YES;  
    12.             //NSLog(@"WIFI");  
    13.             break;  
    14.         case ReachableViaWWAN:  
    15.             isExistenceNetwork = YES;  
    16.             //NSLog(@"3G");  
    17.             break;  
    18.     }  
    19.       
    20.     if (!isExistenceNetwork) {  
    21.         MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];//<span style="font-family: Arial, Helvetica, sans-serif;">MBProgressHUD为第三方库,不需要可以省略或使用AlertView</span>  
    22.         hud.removeFromSuperViewOnHide =YES;  
    23.         hud.mode = MBProgressHUDModeText;  
    24.         hud.labelText = NSLocalizedString(INFO_NetNoReachable, nil);  
    25.         hud.minSize = CGSizeMake(132.f, 108.0f);  
    26.         [hud hide:YES afterDelay:3];  
    27.         return NO;  
    28.     }  
    29.       
    30.     return isExistenceNetwork;  
    31. }  



    然后在需要判断的地方直接:[self isConnectionAvailable] ,大家看懂了吧,就这么简单。

    所以举一反三,如果你不单单是判断是否网络通畅,而是要判断是WIFI或3G,再写一个isEnableWIFI的方法,具体判断方法就不用再赘述了吧,currentReachabilityStatus判断之。


    是不是很方便?项目更合理了呢?

    copy from http://blog.csdn.net/mad1989/article/details/8987368

  • 相关阅读:
    hive_学习_00_资源帖
    大数据_学习_02_目录贴_大数据学习总结
    hadoop_异常_02_ExitCodeException exitCode=1: chmod: changing permissions of `/ray/hadoop/dfs/data': Operation not permitted
    hbase_异常_05_End of File Exception between local host is: "rayner/127.0.1.1"; destination host is: "localhost":9000;
    hbase_异常_04_util.FSUtils: Waiting for dfs to exit safe mode...
    hbase_异常_03_java.io.EOFException: Premature EOF: no length prefix available
    hbase_异常_02_hbase无法访问16010端口
    hbase_异常_01_Hbase: Failed to become active master
    【HDU】2147 kiki's game
    【HDU】1517 A Multiplication Game
  • 原文地址:https://www.cnblogs.com/wangyang1213/p/5283947.html
Copyright © 2011-2022 走看看