iOS 判断网络类型(3G,4G,Wi-Fi)

来源:互联网 发布:什么是淘宝查号截图 编辑:程序博客网 时间:2024/06/05 17:48

在iOS开发中,常常用到网络类型的判断,不多说直接上代码


[objc] view plain copy
  1. #import "ViewController.h"  
  2.   
  3. @interface ViewController ()  
  4.   
  5. @end  
  6.   
  7. @implementation ViewController  
  8. typedef enum {  
  9.     NETWORK_TYPE_NONE= 0,  
  10.     NETWORK_TYPE_2G= 1,  
  11.     NETWORK_TYPE_3G= 2,  
  12.     NETWORK_TYPE_4G= 3,  
  13.     NETWORK_TYPE_5G= 4,//  5G目前为猜测结果  
  14.     NETWORK_TYPE_WIFI= 5,  
  15. }NETWORK_TYPE;  
  16.   
  17. - (void)viewDidLoad {  
  18.     [super viewDidLoad];  
  19.     // Do any additional setup after loading the view, typically from a nib.  
  20.     NSLog(@"%d",[self getNetworkTypeFromStatusBar]);  
  21. }  
  22.   
  23. - (void)didReceiveMemoryWarning {  
  24.     [super didReceiveMemoryWarning];  
  25.     // Dispose of any resources that can be recreated.  
  26. }  
  27.   
  28.   
  29. ////  网络类型  
  30. -(NETWORK_TYPE)getNetworkTypeFromStatusBar {  
  31.     UIApplication *app = [UIApplication sharedApplication];  
  32.     NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];  
  33.     NSNumber *dataNetworkItemView = nil;  
  34.     for (id subview in subviews) {  
  35.         if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]])     {  
  36.             dataNetworkItemView = subview;  
  37.             break;  
  38.         }  
  39.     }  
  40.     NETWORK_TYPE nettype = NETWORK_TYPE_NONE;  
  41.     NSNumber * num = [dataNetworkItemView valueForKey:@"dataNetworkType"];  
  42.     nettype = [num intValue];  
  43.     return nettype;  
0 0