iOS开发——网络连接判断
2015-12-09 22:01
429 查看
iOS开发必然会涉及网络操作,作为优化用户体验的第一步,在请求网络前,往往首先需要判断客户端是否连接网络,并给用户提示。然后用户才会去进行打开网络或连接WiFi等操作。下面我将会使用苹果提供的Reachability文件去进行网络连接的判断。代码已经上传:
https://github.com/chenyufeng1991/JudgeNetworkConnect 。共有两个案例,下面分别来实现:
【静态判断网络连接】
使用该方法会在你需要判断网络连接的地方执行一次判断,是连接还是未连接的。这里说的静态是该判断只会执行一次,并不会根据当前用户的操作动态判断。首先需要导入Reachability.h ,Reachability.m文件。核心代码实现如下:
#import "ViewController.h"
#import "Reachability.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//在需要的地方执行该判断;
[self testConnection];
}
-(void)testConnection{
NSString *result;
if ([self checkNetworkConnection]) {
result = @"连接网络成功!";
}else {
result = @"连接网络失败!";
}
//这里大家可以使用AlertController来弹出提示框;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:result
delegate:self
cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
}
-(BOOL)checkNetworkConnection
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags) {
printf("Error. Count not recover network reachability flags\n");
return NO;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
return (isReachable && !needsConnection) ? YES : NO;
}
@end
【动态判断网络连接】
比如用户打开了WiFi,程序就会监测到已经打开WiFi。比如用户关闭了网络,程序就会监测到关闭了网络。是根据当前客户端的网络状态实时监测的。该代码是苹果提供的Reachability的Demo,源程序有点复杂,我做了一些简化,方便使用。首先需要导入Reachability.h ,Reachability.m文件。核心代码实现如下:
#import "APLViewController.h"
#import "Reachability.h"
@interface APLViewController ()
@property (nonatomic) Reachability *hostReachability;
@end
@implementation APLViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
NSString *remoteHostName = @"http://www.baidu.com";
self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
[self.hostReachability startNotifier];
[self updateInterfaceWithReachability:self.hostReachability];
}
- (void) reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
[self updateInterfaceWithReachability:curReach];
}
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
if (reachability == self.hostReachability)
{
[self configureTextField: reachability];
}
}
- (void)configureTextField:(Reachability *)reachability
{
//NetworkStatus定义的枚举,
NetworkStatus netStatus = [reachability currentReachabilityStatus];
BOOL connectionRequired = [reachability connectionRequired];
switch (netStatus){
case NotReachable:
{
NSLog(@"网络不可用");
connectionRequired = NO;
break;
}
case ReachableViaWWAN: {
NSLog(@"连接WWAN");
break;
}
case ReachableViaWiFi: {
NSLog(@"当前连接了WiFi");
break;
}
}
if (connectionRequired){
//没有连接网络的操作;
}
}
@end
我们不仅要顺手会用这些代码,如果有时间,可以好好研究该功能的实现机制,会大有益处。
github主页:https://github.com/chenyufeng1991
。欢迎大家访问!
https://github.com/chenyufeng1991/JudgeNetworkConnect 。共有两个案例,下面分别来实现:
【静态判断网络连接】
使用该方法会在你需要判断网络连接的地方执行一次判断,是连接还是未连接的。这里说的静态是该判断只会执行一次,并不会根据当前用户的操作动态判断。首先需要导入Reachability.h ,Reachability.m文件。核心代码实现如下:
#import "ViewController.h"
#import "Reachability.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//在需要的地方执行该判断;
[self testConnection];
}
-(void)testConnection{
NSString *result;
if ([self checkNetworkConnection]) {
result = @"连接网络成功!";
}else {
result = @"连接网络失败!";
}
//这里大家可以使用AlertController来弹出提示框;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:result
delegate:self
cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
}
-(BOOL)checkNetworkConnection
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags) {
printf("Error. Count not recover network reachability flags\n");
return NO;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
return (isReachable && !needsConnection) ? YES : NO;
}
@end
【动态判断网络连接】
比如用户打开了WiFi,程序就会监测到已经打开WiFi。比如用户关闭了网络,程序就会监测到关闭了网络。是根据当前客户端的网络状态实时监测的。该代码是苹果提供的Reachability的Demo,源程序有点复杂,我做了一些简化,方便使用。首先需要导入Reachability.h ,Reachability.m文件。核心代码实现如下:
#import "APLViewController.h"
#import "Reachability.h"
@interface APLViewController ()
@property (nonatomic) Reachability *hostReachability;
@end
@implementation APLViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
NSString *remoteHostName = @"http://www.baidu.com";
self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
[self.hostReachability startNotifier];
[self updateInterfaceWithReachability:self.hostReachability];
}
- (void) reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
[self updateInterfaceWithReachability:curReach];
}
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
if (reachability == self.hostReachability)
{
[self configureTextField: reachability];
}
}
- (void)configureTextField:(Reachability *)reachability
{
//NetworkStatus定义的枚举,
NetworkStatus netStatus = [reachability currentReachabilityStatus];
BOOL connectionRequired = [reachability connectionRequired];
switch (netStatus){
case NotReachable:
{
NSLog(@"网络不可用");
connectionRequired = NO;
break;
}
case ReachableViaWWAN: {
NSLog(@"连接WWAN");
break;
}
case ReachableViaWiFi: {
NSLog(@"当前连接了WiFi");
break;
}
}
if (connectionRequired){
//没有连接网络的操作;
}
}
@end
我们不仅要顺手会用这些代码,如果有时间,可以好好研究该功能的实现机制,会大有益处。
github主页:https://github.com/chenyufeng1991
。欢迎大家访问!
相关文章推荐
- BP神经网络
- 使用httpclient 调用selenium webdriver
- 计算机网络笔试面试常考
- laodRuner中Http协议接口编写
- 黑马程序员--网络编程
- linux系统重启网络delaying initialization错误的解决方法
- 网络层—IP多播
- 【高可用HA】Nginx (1) —— Mac下配置Nginx Http负载均衡(Load Balancer)之101实例
- linux下tcpdump详解
- CentOS---网络配置详解
- 关于基于复杂网络的数据挖掘的学习笔记
- 跨平台c++/boost/asio 简单的HTTP POST请求 客户端模型
- ASP.NET5 MVC6 利用Middleware 创建可访问HttpContext 的业务类工厂。(代替HttpContext.Current)
- Volley框架之四 加载网络图片
- 1491: [NOI2007]社交网络
- HTTP 错误 404.3 -Not Found---如何从报错的提示内容来寻找最佳解决方案?
- TCP/IP-协议族----17、应用层简单
- 【iOS】MD5数据加密和网络安全
- Xcode7 —https适配问题
- 网络层—路由器的构成