iOS开发——网络连接判断

       iOS开发必然会涉及网络操作,作为优化用户体验的第一步,在请求网络前,往往首先需要判断客户端是否连接网络,并给用户提示。然后用户才会去进行打开网络或连接WiFi等操作。下面我将会使用苹果提供的Reachability文件去进行网络连接的判断。代码已经上传: https://github.com/chenyufeng1991/JudgeNetworkConnect   。共有两个案例,下面分别来实现:

【静态判断网络连接】

使用该方法会在你需要判断网络连接的地方执行一次判断,是连接还是未连接的。这里说的静态是该判断只会执行一次,并不会根据当前用户的操作动态判断。首先需要导入Reachability.h ,Reachability.m文件。核心代码实现如下:

#import "ViewController.h"
#import "Reachability.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  //在需要的地方执行该判断;
  [self testConnection];

}

-(void)testConnection{
  NSString *result;
  if ([self checkNetworkConnection]) {
    result = @"连接网络成功!";
  }else {
    result = @"连接网络失败!";
  }
  
  //这里大家可以使用AlertController来弹出提示框;
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:result
                                                 delegate:self
                                        cancelButtonTitle:@"确定" otherButtonTitles:nil];
  [alert show];
  
}

-(BOOL)checkNetworkConnection
{
  struct sockaddr_in zeroAddress;
  bzero(&zeroAddress, sizeof(zeroAddress));
  zeroAddress.sin_len = sizeof(zeroAddress);
  zeroAddress.sin_family = AF_INET;
  
  SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
  SCNetworkReachabilityFlags flags;
  
  BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
  CFRelease(defaultRouteReachability);
  
  if (!didRetrieveFlags) {
    printf("Error. Count not recover network reachability flags\n");
    return NO;
  }
  
  BOOL isReachable = flags & kSCNetworkFlagsReachable;
  BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
  return (isReachable && !needsConnection) ? YES : NO;
}

@end


【动态判断网络连接】

比如用户打开了WiFi,程序就会监测到已经打开WiFi。比如用户关闭了网络,程序就会监测到关闭了网络。是根据当前客户端的网络状态实时监测的。该代码是苹果提供的Reachability的Demo,源程序有点复杂,我做了一些简化,方便使用。首先需要导入Reachability.h ,Reachability.m文件。核心代码实现如下:

#import "APLViewController.h"
#import "Reachability.h"


@interface APLViewController ()

@property (nonatomic) Reachability *hostReachability;

@end




@implementation APLViewController

- (void)viewDidLoad
{
  [super viewDidLoad];
  
  
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  
  NSString *remoteHostName = @"http://www.baidu.com";
  
  self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
  [self.hostReachability startNotifier];
  [self updateInterfaceWithReachability:self.hostReachability];

}



- (void) reachabilityChanged:(NSNotification *)note
{
  Reachability* curReach = [note object];
  [self updateInterfaceWithReachability:curReach];
}


- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
  if (reachability == self.hostReachability)
  {
    [self configureTextField: reachability];
    
    
  }
}


- (void)configureTextField:(Reachability *)reachability
{
  //NetworkStatus定义的枚举,
  NetworkStatus netStatus = [reachability currentReachabilityStatus];
  BOOL connectionRequired = [reachability connectionRequired];
  
  switch (netStatus){
    case NotReachable:
    {
      
      NSLog(@"网络不可用");
      
      connectionRequired = NO;
      break;
    }
      
    case ReachableViaWWAN:        {
      NSLog(@"连接WWAN");
      break;
    }
    case ReachableViaWiFi:        {
      
      NSLog(@"当前连接了WiFi");
      break;
    }
  }
  
  if (connectionRequired){
    //没有连接网络的操作;
  }
}


@end


      我们不仅要顺手会用这些代码,如果有时间,可以好好研究该功能的实现机制,会大有益处。



github主页:https://github.com/chenyufeng1991  。欢迎大家访问!

  • 4
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值