您的位置:首页 > 移动开发 > IOS开发

iOS检测联网

2015-11-20 20:20 423 查看
在ios移动开发过程中,只要不是单机的移动的开发,基本都有链接网络的操作。这次主要讲的是用Reachability来判断iphone是否处于联网状态中。

首先,苹果官网提供了Reachability的接口。

https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html

在这里,可以下载Reachability.m和Reachability.h,然后将这两个文件导入到自己的项目里面。

官网给出的主要是三种状态:

网络不可用:NoteReachable

使用的是本地运营商网络:ReachableViaWiFi

使用的Wi-Fi网络:ReachableViaWWAN

接口代码如下:

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


然后,就需要在自己的代码里面调用相应的接口。

在官网给定的接口中,可以判断出来是WI-FI连接还是本地运营商链接。代码如下:

- (void)testConnection {
BOOL result = YES;
Reachability *reach=[Reachability sharedReachability];
[reach setHostName:@“www.baidu.com”];
NetworkStatus status;
status=[reach remoteHostStatus];
//本地运营商
{
[AlertView showNotice:@"使用本地网络"];
}
//WI-FI连接
else if (status == ReachableViaWiFiNetwork)
{
[AlertView showNotice:@"使用WIFI网络"];
}
}


如果仅仅是判断iphone是否处于联网状态中,那就需要改动一下Reachability.m和Reachability.h这两个文件,在里面添加一些判定的代码。

Reachability.h

typedef void (^NetworkReachable)(Reachability * reachability);
typedef void (^NetworkUnreachable)(Reachability * reachability);
@interface Reachability : NSObject
@property (nonatomic, copy) NetworkReachable    reachableBlock;
@property (nonatomic, copy) NetworkUnreachable  unreachableBlock;


Reachability.m

#if NEEDS_DISPATCH_RETAIN_RELEASE
@property (nonatomic, assign) dispatch_queue_t          reachabilitySerialQueue;
#else
@property (nonatomic, strong) dispatch_queue_t          reachabilitySerialQueue;
#endif


在需要检测网络连接的相应View Controller中加入如下代码:

Reachability *reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
reach.reachableBlock = ^(Reachability *reach)
{
dispatch_async(dispatch_get_main_queue(), ^{
[reach stopNotifier];
//提示网络可达
[AlertView showNotice:@"网络正常"];
});
};
reach.unreachableBlock = ^(Reachability*reach)
{
dispatch_async(dispatch_get_main_queue(), ^{
[reach stopNotifier];
//提示网络不可达
[AlertView showNotice:@"您处于离线模式(网络缺失)"];
});
};
// start the notifier which will cause the reachability object to retain itself!
[reach startNotifier];


最后运行出来的效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 移动开发