iPhone 开发之网络检查

jopen 12年前

最近做一个项目要频繁的进行网络操作,但有时需要判定网络状态和当前网络的类型。看到好多前辈都是使用

reachability来实现的。我也试了试效果还不错,封装成了工具类方便大家使用。

使用说明

    1.添加framework 

    SystemConfiguration.framework添加进工程。 

    2.下载https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip

    复制里面的Reachability.hReachability.m到项目中

    3.添加CloNetworkUtil.h和CloNetworkUitl.m到你的项目中

     在使用的地方导入CloNetworkUtil.h头文件即可

CloNetworkUtil.h代码:

//    //  CloNetworkUtil.h    //  NetWorkTest    //    //  Created by Cloay on 12-6-19.    //  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.    /**       1.添加framework:        将SystemConfiguration.framework 添加进工程。        2.下载 https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip       复制里面的Reachability.h和Reachability.m到项目中   */        #import     #import "Reachability.h"    @interface CloNetworkUtil : NSObject{    }            - (Reachability *)initReachability;    - (BOOL)getNetWorkStatus;    - (NSString *)getNetWorkType;    @end 
实现如下:
//        //  CloNetworkUtil.m        //  NetWorkTest        //        //  Created by Cloay on 12-6-19.        //  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.        //                #import "CloNetworkUtil.h"                @implementation CloNetworkUtil                //初始化reachability        - (Reachability *)initReachability{            Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];            return reachability;        }                //判断网络是否可用        - (BOOL)getNetWorkStatus{            if ([[self initReachability] currentReachabilityStatus] == NotReachable) {                return NO;            }else {                return YES;            }        }                /**        获取网络类型        return        */        - (NSString *)getNetWorkType        {            NSString *netWorkType;            Reachability *reachability = [self initReachability];            switch ([reachability currentReachabilityStatus]) {                case ReachableViaWiFi:   //Wifi网络                    netWorkType = @"wifi";                    break;                case ReachableViaWWAN:  //无线广域网                    netWorkType = @"wwan";                     break;                default:                    netWorkType = @"no";                    break;            }            return netWorkType;        }                @end  

很简单就不在说明了!效果图:

iPhone 开发之网络检查

转自:http://blog.csdn.net/shang_515/article/details/7697149