将3G检测添加到以下代码中

时间:2014-03-10 16:43:44

标签: ios objective-c reachability

我有一种检查 Wi-Fi 的方法,这是我从一个旧项目获得的,现在我需要实际检查 3G 或< strong> Wifi ,如果没有,则提供错误消息。

原始样本工作:

- (BOOL)checkForWIFIConnection {

    Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];
    NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
    if (netStatus!=ReachableViaWiFi)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Sem conexão à internet!", @"AlertView")
                                                            message:NSLocalizedString(@"Não está conectado à internet. Tente novamente após se connectar.", @"AlertView")
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"OK", @"AlertView")
                                                  otherButtonTitles: nil];
        [alertView show];
        return NO;
    }
    else {
        return YES;
    }
}

如何检查ReachableViaWWAN?我可以在这里添加它(&lt ;-) ??

- (BOOL)checkForWIFIConnection {

        Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];
        NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
        if (netStatus!=ReachableViaWiFi && ReachableViaWWAN) <- (i get an error saying use of logical && with constant operand)
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Sem conexão à internet!", @"AlertView")
                                                                message:NSLocalizedString(@"Não está conectado à internet. Tente novamente após se connectar.", @"AlertView")
                                                               delegate:self
                                                      cancelButtonTitle:NSLocalizedString(@"OK", @"AlertView")
                                                      otherButtonTitles: nil];
            [alertView show];
            return NO;
        }
        else {
            return YES;
        }
    }

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

简单地改变:

Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];

为:

Reachability* wifiReach = [Reachability reachabilityForInternetConnection];

if (netStatus!=ReachableViaWiFi)

为:

if (netStatus == NotReachable)

换句话说:

Reachability* wifiReach = [Reachability reachabilityForInternetConnection];
NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
if (netStatus == NotReachable)
{

BTW - 请参阅Objective-C教程以了解如何编写复合表达式。您的if声明必须类似于:

if (netStatus!=ReachableViaWiFi && netStatus!=ReachableViaWWAN)

虽然这会解决编译器问题,但它不适用于您的代码,因为使用WWAN时不会给出reachabilityForLocalWiFi值。