首页 文章

确定iPhone互联网连接是否可用的最简单方法?

提问于
浏览
12

我想确定iPhone上是否有互联网连接 . 对于应用程序来说无论是wifi还是EDGE或其他什么都无关紧要 .

使用SeismicXML示例中的代码似乎不起作用,Apple的Reachability示例代码似乎对应用程序来说太过分了......

有没有一种快速简便的方法来确定iPhone上的网络可用性?

谢谢,本

6 回答

  • 5

    Follow following 3 easy steps -

    Step 1: 在项目中包含"SystemConfiguration.framework"框架

    Step 2: 包含Apple的Reachability.h和Reachability.m来自可达性示例

    Step 3: 现在将此代码添加到.m中的任何位置 .

    Reachability* wifiReach = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain];
    NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
    
    switch (netStatus)
    {
        case NotReachable:
        {
            NSLog(@"Access Not Available");
            break;
        }
    
        case ReachableViaWWAN:
        {
            NSLog(@"Reachable WWAN");
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"Reachable WiFi");
            break;
        }
    }
    
  • 0

    我从他们的Reachability示例中加入了Apple的Reachability.h和.m,再加上上面提到的SystemConfiguration框架,然后将以下代码添加到我的应用程序中,这比上面的答案有两个优点 - 它为您提供了更多信息,并且您获得了异步网络状态更改通知 .

    在您的app delegate或类似代码中,在启动时添加:

    [self startReachability];
    

    然后添加此方法,在网络更改时调用该方法:

    #pragma mark Reachability changed
    - (void)reachabilityChanged:(NSNotification*)aNote
    {
    self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];
    
    switch (self.remoteHostStatus)
    {
    case NotReachable:
      debugForComponent(kDebugMaskApp,@"Status changed - host not reachable");
      break;
    
    case ReachableViaCarrierDataNetwork:
      debugForComponent(kDebugMaskApp,@"Status changed - host reachable via carrier");
      break;
    
    case ReachableViaWiFiNetwork:
      debugForComponent(kDebugMaskApp,@"Status changed - host reachable via wifi");     
      break;
    
    default:
      debugForComponent(kDebugMaskApp,@"Status changed - some new network status");
      break;
    }
    }
    
  • 7

    一旦尝试复制SystemConfiguration.framework,我在破解XCode之后想出来......这是对任何可能感兴趣的人的解决方案......

    将SystemConfiguration.framework添加到项目中,执行#import <SystemConfiguration / SystemConfiguration.h>,然后添加以下代码:

    SCNetworkReachabilityFlags flags;
    BOOL receivedFlags;
    
    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(CFAllocatorGetDefault(), [@"google.com" UTF8String]);
    receivedFlags = SCNetworkReachabilityGetFlags(reachability, &flags);
    CFRelease(reachability);
    
    if (!receivedFlags || (flags == 0) )
    {
        // internet not available
    } else {
        // internet available
    }
    

    嗯,希望这对任何人都有帮助...似乎是让应用被拒绝的常见方式......

  • 1
  • 24

    这是解决您问题的最快捷,最简单的解决方案:

    ([NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]]!=NULL)?YES:NO;
    

    如果已连接,它将返回 YES ,如果不连接,则返回 NO . 它只是尝试加载谷歌,如果它成功,它返回 YES .

    然后你可以得到一个带有返回值的 if 语句,这样你就可以抛出一个通知或者你喜欢的任何东西 .

  • 9

    我的第一个想法是看看我是否可以连接到谷歌 .

相关问题