最近做一個項目要頻繁的進行網絡操作,但有時需要判定網絡狀態和當前網絡的類型。看到好多前輩都是使用
reachability來實現的。我也試了試效果還不錯,封裝成了工具類方便大家使用。
使用說明:
1.添加framework:
將SystemConfiguration.framework添加進工程。
2.下載https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
復制裡面的Reachability.h和Reachability.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 <Foundation/Foundation.h>
- #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
很簡單就不在說明了!效果圖: