美文网首页
使用AFNetWorking 监听网络

使用AFNetWorking 监听网络

作者: emily_sky | 来源:发表于2016-08-24 10:58 被阅读44次
    #import "AppDelegate.h"
    
    #import <AFNetworking/AFNetworkReachabilityManager.h>
    
    @interface AppDelegate ()
    @property(nonatomic,strong)NSString *netStr;
    @property(nonatomic,strong)AFNetworkReachabilityManager *manager;
    @end
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    
        //网络监听
        [self netWorkMonitoringAction];
    }
    
    -(void)netWorkMonitoringAction{
        //创建网络监听管理者对象
        _manager = [AFNetworkReachabilityManager sharedManager];
        __weak typeof (self) weakSelf  =self;
        //设置监听网络状态
        [_manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusUnknown:
                    weakSelf.netStr = @"未识别的网络";
                    break;
                case AFNetworkReachabilityStatusNotReachable:{
                weakSelf.netStr = @"未连接网络";
                }
                    break;
                case AFNetworkReachabilityStatusReachableViaWiFi:{
                    weakSelf.netStr = @"已连接wifi";
                }
                    break;
                case AFNetworkReachabilityStatusReachableViaWWAN:{
                    weakSelf.netStr = @"正在使用2G,3G,4G网络";
                }
                   break;
                default:
                    break;
            }
            [weakSelf drawNetWorkLayer:weakSelf.netStr];
            }];
            //开始监听
            [_manager startMonitoring];
    }
    
    -(void)dealloc{ 
        //停止监听网络状况.
         [_manager stopMonitoring];
    }
    
    - (void)drawNetWorkLayer:(NSString *)string{
        CGRect rect = [string boundingRectWithSize:CGSizeMake(ScreenWidth-16, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
        UILabel *netWorkLayer = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth/2-(rect.size.width+50)/2, ScreenHeigth/2-50, rect.size.width+50, 30)];
        netWorkLayer.text = string;
        netWorkLayer.textColor = [UIColor whiteColor];
        netWorkLayer.layer.cornerRadius = 5;
        netWorkLayer.layer.masksToBounds = YES;
        netWorkLayer.backgroundColor = [UIColor blackColor];
        netWorkLayer.textAlignment = NSTextAlignmentCenter;
    
        [self.window addSubview:netWorkLayer];
    
        [UIView animateWithDuration:5.0 animations:^{
            netWorkLayer.alpha = 0.0;
        
        }];
    
    }

    相关文章

      网友评论

          本文标题:使用AFNetWorking 监听网络

          本文链接:https://www.haomeiwen.com/subject/vhansttx.html