iOS检测联网

在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];

最后运行出来的效果图:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值