现在的位置: 首页 > 综合 > 正文

iPhone开发之确认网络环境

2019年10月01日 ⁄ 综合 ⁄ 共 2045字 ⁄ 字号 评论关闭

开发网络应用程序的时候,需要确认网络环境及连接情况等信息。如果没有处理它们,是不会通过Apple的审查的。

1. 添加源文件及Framework

Apple 的官方例子 Reachability 中介绍了获取、检测设备当前网络状态的方法。在你的程序中,需要把该工程中的Reachability.h 和 Reachability.m 拷贝到你的工程中,同时需要把 SystemConfiguration.framework 添加到工程中,

如下图:

Reachability.h 中定义了三种网络状态:

typedef enum {
	NotReachable = 0,
	ReachableViaWiFi,
	ReachableViaWWAN
} NetworkStatus;

1) NotReachable

表示无连接

2) ReachableViaWiFi

使用 WiFi 网络连接

3) ReachableViaWWAN

使用 3G / GPRS网络

2 网络连接状态实时通知

当用户的网络状态发生改变时,需要实时通知用户。代码如下所示:

AppDelegate.h:

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

@interface AppDelegate : UIResponder <UIApplicationDelegate> {
    Reachability *_reach;
    NetworkStatus _status;
}

@property (strong, nonatomic) UIWindow *window;

@end

AppDelegate.m:

#import "AppDelegate.h"


@implementation AppDelegate

@synthesize window = _window;

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_reach release];
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    [self startWatchingNetworkStatus];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

#pragma mark Network Watching
- (void)startWatchingNetworkStatus {
    //监测网络状况
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    _reach = [Reachability reachabilityWithHostName:@"www.google.com"];
    [_reach startNotifier];
    _status = ReachableViaWiFi;
}

- (void)reachabilityChanged:(NSNotification* )note {
    Reachability *curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    
    //检测站点的网络连接状态
    NetworkStatus curStatus = [curReach currentReachabilityStatus];
    if (curStatus != _status) {
        NSString *str = nil;
        
        //根据不同的网络状态,UI或者程序中关于数据的下载需要做出相应的调整,自己实现
        switch (curStatus) {
            case NotReachable:
                str = @"网络不可用";
                break;
            case ReachableViaWiFi:
                str = @"wifi网络可用";
                break;
            case ReachableViaWWAN:
                str = @"3G/GPRS网络可用";
                break;
                
            default:
                str = @"未知网络";
                break;
        }
        NSLog(@"%@", str);
    }
    
    _status = curStatus;
}
@end

抱歉!评论已关闭.