首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查网络可用性

检查网络可用性
EN

Stack Overflow用户
提问于 2012-09-08 14:00:09
回答 3查看 683关注 0票数 0

我使用reacheability类来检查我的应用程序中的网络连接...

代码语言:javascript
复制
Reachability *reach = [Reachability reachabilityForInternetConnection]; 
    NetworkStatus netStatus = [reach currentReachabilityStatus];    
    if (netStatus==NotReachable)
    {
        NSLog(@"NR");
    }

我需要找出网络状态何时改变(即网络状态何时从可达变为不可达,反之亦然)。

有没有代表找到这个想法,有什么建议?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-25 18:06:49

使用此标志kReachabilityChangedNotification查找网络状态的更改,并将其传递给NSNotificationCenter

代码如下:

代码语言:javascript
复制
NSString *host = @"https://www.apple.com"; // Put your host here

        // Set up host reach property
       hostReach = [Reachability reachabilityWithHostname:host];

                          // Enable the status notifications
                          [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
                           [hostReach startNotifier];

   - (void) reachabilityChanged: (NSNotification* )note
{
    Reachability *reachability = [note object];
    NSParameterAssert([reachability isKindOfClass:[Reachability class]]);
    if (reachability == hostReach) {
        Reachability *reach = [Reachability reachabilityForInternetConnection]; 
        NetworkStatus netStatus = [reach currentReachabilityStatus];    
        if (netStatus==NotReachable)
        {
            NSLog(@"notreacheable");
        }
        else {
            NSLog(@"reacheable");
            [[NSNotificationCenter defaultCenter]postNotificationName:@"startUpdatingTable" object:nil];
        }
    }
}
票数 0
EN

Stack Overflow用户

发布于 2012-09-08 14:11:23

我建议使用Apple的可达性类。Here是苹果的一个示例应用程序。

并检查此链接。

http://www.switchonthecode.com/tutorials/iphone-snippet-detecting-network-status

票数 1
EN

Stack Overflow用户

发布于 2012-09-08 14:58:14

使用可达性“

在应用程序委托中添加泛洪方法,以便可以在项目中的任何软件中使用此方法

代码语言:javascript
复制
#import "Reachability.h"
-(BOOL)isHostAvailable
{
    //return NO; // force for offline testing
    Reachability *hostReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [hostReach currentReachabilityStatus];
    return !(netStatus == NotReachable);
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12328445

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档