edcf 发表于 2015-10-1 10:36:04

判断网络环境(3G/WIFI)

  通过Reachability来判断设备的网络环境,方法比较简单。直接将Reachability.h和Reachability.m加入到工程中,然后添加SystemConfiguration.framework框架,就可以使用了。工程截图:

  ViewController.h



//
//ViewController.h
//NetworkStatusDemo
//
//Created by Fox on 12-3-15.
//Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Reachability.h"
@interface ViewController : UIViewController{
    IBOutlet UILabel *netstatus;
    Reachability* status; //网络状态

}
@property (retain, nonatomic) IBOutlet UILabel *netstatus;
@property (retain, nonatomic) Reachability* status;
+ (BOOL) IsEnableWIFI;
+ (BOOL) IsEnable3G;
@end
  
  ViewController.m



//
//ViewController.m
//NetworkStatusDemo
//
//Created by Fox on 12-3-15.
//Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "Reachability.h"
@implementation ViewController
@synthesize netstatus;
@synthesize status;

- (void)viewDidLoad
{
    ;
    self.status = [ init];
    status = ;
    switch () {
      case NotReachable:
            // 没有网络连接
            self.netstatus.text = @"没有网络连接";
            break;
      case ReachableViaWWAN:
            // 使用3G网络
            self.netstatus.text = @"使用3G网络";
            break;
      case ReachableViaWiFi:
            // 使用WiFi网络
            self.netstatus.text = @"使用WiFi网络";
            break;
    }
    //程序启动时,检查程序的网络环境
    if ( && !) {
      self.netstatus.text = @"使用WiFi网络";
    }else if(! && ){
      self.netstatus.text = @"使用3G网络";
    }elseself.netstatus.text = @"没有网络连接";
}
- (void)viewDidUnload
{
    ;
    ;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void)dealloc {
    ;
    ;
}

/*
*判断是否通过wifi
*/
+ (BOOL) IsEnableWIFI {
    return ([ currentReachabilityStatus] != NotReachable);
}
/*
*判断是否通过3G
*/
+ (BOOL) IsEnable3G {
    return ([ currentReachabilityStatus] != NotReachable);
}

@end
页: [1]
查看完整版本: 判断网络环境(3G/WIFI)