iOS 检测网络状态

引入三方库:

pod "Reachability"

 

ZLBNetworkReachablity.h

//
//  ZLBNetworkReachablity.h
//  ZLBiPhone
//
//  Created by xujinzhong on 14-5-26.
//  Copyright (c) 2016年 zzll. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Reachability.h"

@interface ZLBNetworkReachablity : NSObject

//判断网络连接状态
+ (BOOL)getNetWorkStatus;

//返回网络类型
+ (NSString *)getNetWorkType;

@end

 

ZLBNetworkReachablity.m

//
//  ZLBNetworkReachablity.m
//  ZLBiPhone
//
//  Created by xujinzhong on 14-5-26.
//  Copyright (c) 2016年 zzll. All rights reserved.
//

#import "ZLBNetworkReachablity.h"
#import "Reachability.h"

@interface ZLBNetworkReachablity ()
@end

@implementation ZLBNetworkReachablity

/**
 *    @brief 判断网络是否可用
 *
 */
+ (BOOL)getNetWorkStatus
{
    Reachability  *hostReach = [Reachability reachabilityForInternetConnection];
    switch ([hostReach currentReachabilityStatus]){
        case NotReachable:
            break;
        case ReachableViaWWAN:
            return YES;
        case ReachableViaWiFi:
            return YES;
    }
    return NO;
}

/**
 *    @brief 获取网络类型
 *
 */
+ (NSString *)getNetWorkType
{
    NSString *netWorkType;
    Reachability  *hostReach = [Reachability reachabilityForInternetConnection];
    switch ([hostReach currentReachabilityStatus]){
        case NotReachable:
            break;
        case ReachableViaWWAN:
            netWorkType = @"M";
            break;
        case ReachableViaWiFi:
            netWorkType = @"WIFI";
            break;
        default:
            netWorkType = @"无网";
            break;
    }
    return netWorkType;
}

@end

posted on 2018-02-27 15:32  东方&#128058;  阅读(92)  评论(0编辑  收藏  举报

导航