Reachability的使用和方法介绍和NSAssert、NSParameterAssert的使用

前言:

       APP 开的过程中,网络占有主要的地位,同时,网络的变化时我们应该做出什么样的处理,这也是很重要的。有得时候APP开发我们都忘记处理网络变化的事件。今天,我就简单介绍网络变化的监控。

效果:效果展示



正文:代码的进入  

//

//  ViewController.m

//  NetAlert

//

//  Created by 周双建 on 16/4/15.

//  Copyright © 2016周双建. All rights reserved.

//


#import "ViewController.h"

#import "Reachability.h"


@interface ViewController ()

@property (nonatomic)Reachability *hostReachability;

@property(nonatomic,strong)UIView * AllscreenView;

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(reachabilityChanged:)name:kReachabilityChangedNotificationobject:nil];

    // 用可用的网站地址,设置检查站点

    self.hostReachability = [ReachabilityreachabilityWithHostName:@"www.baidu.com"];

    [self.hostReachabilitystartNotifier];

    Reachability * internetReach = [ReachabilityreachabilityForInternetConnection];

    [internetReach startNotifier];

    Reachability * wifiReach = [ReachabilityreachabilityForLocalWiFi] ;

    [wifiReach startNotifier];

    /*!

     *  + (instancetype)reachabilityWithHostName:(NSString *)hostName;

     *  @ hostName  是你设置的站点的网址(一般用百度,也可以使用其他的)

     */

    /*!

     *  + (instancetype)reachabilityForInternetConnection;

     *  Checks whether the default route is available. Should be used by applications that do not connect to a particular host.

     *  这是随机选择可用的路由,作为检查站点

     *  例子:

     *  Reachability * KReachability = [Reachability  reachabilityForInternetConnection];

     */

    /*!

     *  + (instancetype)reachabilityForLocalWiFi;

     *  这是选择局部的wifi作为检查站点

     *  例子:

     *  Reachability * KReachability = [Reachability  reachabilityForLocalWiFi];

     */

    /*!

     *  + (instancetype)reachabilityWithAddress:(const struct sockaddr_in *)hostAddress;

     *  这是使用一个指定的IP作为网络的检查站点

     *  例子:

     *  Reachability * KReachability = [Reachability  reachabilityWithAddress:@"121.1268.2.1"];

     */

    

    /*************************************************************************************/

    /*!

     * 下面两个方法的解释

     * Start listening for reachability notifications on the current run loop.

     */


    /*!

     *  - (BOOL)startNotifier

     *  开启网络变化监控

     *  例子:

     *      [KReachability startNotifier];

     */

    [self.hostReachabilitystartNotifier];

    /*!

     *  - (void)stopNotifier

     *  停止网络变化,监控

     *  例子:

     *      [KReachability stopNotifier];

     */

    [self.hostReachabilitystopNotifier];

    /*************************************************************************************/


    // 得到网络检查的对象,首先,我们要获取网络是什么状态

    /*!

     *   - (NetworkStatus)currentReachabilityStatus

     *   这是获取网络的状态

         typedef enum : NSInteger {

                 NotReachable = 0,     // 无网络

                 ReachableViaWiFi,     // wifi 网络状态下

                 ReachableViaWWAN      // GE网络状态下

         } NetworkStatus;

     */

    switch (self.hostReachability.currentReachabilityStatus) {

        caseNotReachable:{

            NSLog(@"无网络连接");

            _AllscreenView = [[UIViewalloc]initWithFrame:CGRectMake(10,20, self.view.bounds.size.width-20,40)];

            _AllscreenView.layer.borderWidth =0.5;

            _AllscreenView.layer.cornerRadius =10;

            _AllscreenView.layer.backgroundColor = [[UIColorlightTextColor] colorWithAlphaComponent:0.6].CGColor;

            CATransition * Animation = [CATransitionanimation];

            Animation.type = kCATransitionPush;

            Animation.timeOffset = 2;

            UILabel * ScreenLabel = [[UILabelalloc]initWithFrame:CGRectMake(0,0, CGRectGetWidth(_AllscreenView.frame),40)];

            ScreenLabel.textAlignment = NSTextAlignmentCenter;

            ScreenLabel.text = @"你网络异常,请检查网络";

            ScreenLabel.textColor = [UIColorredColor];

            [_AllscreenView addSubview:ScreenLabel];

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{

                [_AllscreenView.layeraddAnimation:Animation forKey:nil];

                [[UIApplicationsharedApplication].keyWindowaddSubview:_AllscreenView];

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{

                    [_AllscreenView removeFromSuperview];

                });

            });

            // 进行APP页面跳转

            NSURL*url =[NSURLURLWithString:@"prefs:root=WIFI"];

            [[UIApplicationsharedApplication] openURL:url];

        }

            break;

        caseReachableViaWWAN:{

            NSLog(@"G网络状态下");

            UIAlertController * AlertController = [UIAlertControlleralertControllerWithTitle:@"温馨提示"message:@"您在G网络下,是否继续"preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction * SureAction = [UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction *_Nonnull action) {

                  // G网络状态可以的情况下,但是就是没有网络连接

                /*!

                 *  - (BOOL)connectionRequired;

                 *  WWAN may be available, but not active until a connection has been established. WiFi may require a connection for VPN on Demand.

                 *  例子:

                 *  BOOL Content = [KReachability connectionRequired];

                 */

                BOOL Content = [self.hostReachabilityconnectionRequired];

                if (!Content) {

                    NSLog(@"网络转接失败");

                }

            }];

            UIAlertAction * CancleAction = [UIAlertActionactionWithTitle:@"取消"style:UIAlertActionStyleCancelhandler:^(UIAlertAction *_Nonnull action) {

                

            }];

            [AlertController addAction:CancleAction];

            [AlertController addAction:SureAction];

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{

                [self presentViewController:AlertController animated:YEScompletion:nil];

            });

        }

            break;

        caseReachableViaWiFi:{

            NSLog(@"Wifi状态下");

            NSURL*url =[NSURLURLWithString:@"prefs:root=WIFI"];

            [[UIApplicationsharedApplication] openURL:url];


        }

            break;

        default:

            break;

    }

    BOOL  TestBool = YES;

    NSAssert(TestBool, @"发生警告");

    

    // Do any additional setup after loading the view, typically from a nib.

}

// 网络监控变化

-(void)reachabilityChanged:(NSNotification*)Notification{

    // 获取观察对象

    Reachability *curReach = [Notification object];

    // 获取一个断言句柄,如果条件成立,程序可执行,否则,程序会抛出异常

    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);

    [selfupdateInterfaceWithReachability:curReach];

}

- (void)updateInterfaceWithReachability:(Reachability *)curReach{

    if (curReach == self.hostReachability) {

        NSLog(@"网络发生变化了");

    }

}

- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

-(void)dealloc{

    // 移除观察者

    [[NSNotificationCenterdefaultCenter] removeObserver:kReachabilityChangedNotificationname:nilobject:self];

}

@end


友情客串
一: NSAssert

NSAssert:

NSAssert()只是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()传递条件表达式来断定是否属于Bug,满足条件返回真值,程序继续运行,如果返回假值,则抛出异常,并切可以自定义异常描述。NSAssert()是这样定义的:

#define NSAssert(condition, desc)

condition是条件表达式,值为YES或NO;desc为异常描述,通常为NSString。当conditon为YES时程序继续运行,为NO时,则抛出带有desc描述的异常信息。NSAssert()可以出现在程序的任何一个位置。


使用:(介绍错误的使用)

    BOOL  TestBool =NO;

    NSAssert(TestBool,@"发生警告");


抛出的异常



第二:NSParameterAssert

NSParameterAssert

断言评估一个条件,如果条件为 false ,调用当前线程的断点句柄。每一个线程有它自已的断点句柄,它是一个 NSAsserttionHandler 类的对象。当被调用时,断言句柄打印一个错误信息,该条信息中包含了方法名、类名或函数名。然后,它就抛出一个 NSInternalInconsistencyException 异常。
(官方:Assertions evaluate a condition and, if the condition evaluates to false, call the assertion handler for the current thread, passing it a format string and a variable number of arguments. Each thread has its own assertion handler, which is an object of classNSAssertionHandler. When invoked, an assertion handler prints an error message that includes method and class names (or the function name). It then raises anNSInternalInconsistencyException exception.)

这个宏用于确认一个 Objective-C 的方法的有效性。简单提供参数作为条件就行。该宏评估这个参数,如果为 false ,它就打印一个错误日志信息,该信息包含了参数并且抛出一个异常。
官方:This macro validates a parameter for an Objective-C method. Simply provide the parameter as the condition argument. The macro evaluates the parameter and, if it is false, it logs an error message that includes the parameter and then raises an exception.)

如果定义了预处理宏 NS_BLOCK_ASSERTIONS 断言就被禁止了。所有的断点宏都返回 void。
官方:Assertions are disabled if the preprocessor macro NS_BLOCK_ASSERTIONS is defined. All assertion macros return void.)

使用:

     Reachability *curReach = [Notification object];

    // 获取一个断言句柄,如果条件成立,程序可执行,否则,程序会抛出异常

     NSParameterAssert([curReach isKindOfClass:[NSString  class]]);

    [selfupdateInterfaceWithReachability:curReach];





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值