ios - 如何检查 ios 中的互联网连接?

标签 ios objective-c notifications nsnotificationcenter

如何检查应用程序是否已连接到互联网? 目前,我在我的 appdelegate.m 文件中使用这段代码

dispatch_queue_t connectivityThread = dispatch_queue_create("com.gm.kart.connectivity", NULL);

dispatch_async(connectivityThread, ^{
    while (true){
        if([GMMConnectivity hasConnectivity])
            NSLog(@"%@", @"connected");
        else
            NSLog(@"Not connected");

        usleep(10000000);
    }
});

当我点击登录按钮时,我想使用 NSnotificationcenter 检查互联网是否已连接?

请帮帮我

最佳答案

下载以下示例后。

http://developer.apple.com/iphone/library/samplecode/Reachability/index.html

您可以在您的项目中使用它,如下所示:-

从其 Reachability 示例中包含 Apple 的 Reachability.h & .m。

添加 SystemConfiguration 框架。

将波纹管方法放入您的 appdelegare.m 文件中:-

- (BOOL) connectedToNetwork{
    Reachability* reachability = [Reachability reachabilityWithHostName:@"google.com"];
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

    if(remoteHostStatus == NotReachable)
    {
        isInternet =NO;
    }
    else if (remoteHostStatus == ReachableViaWWAN)
    {
        isInternet = TRUE;
    }
    else if (remoteHostStatus == ReachableViaWiFi)
    { isInternet = TRUE;

    }
    return isInternet;
}

isInternet 是 .h 类中的 BOOL 声明

根据您的代码:-

dispatch_queue_t connectivityThread = dispatch_queue_create("com.GMM.assamkart.connectivity", NULL);

dispatch_async(connectivityThread, ^{
    while (true){
       isInternet =[self connectedToNetwork];
    if (isInternet)
    {
           NSLog(@"connected");
        }
        else
        {
            NSLog(@"Not connected");
        }
       // usleep(10000000);
    }
});

关于ios - 如何检查 ios 中的互联网连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16057098/

相关文章:

ios - UIViewAnimationOptions.TransitionFlipFromLeft 第二次不显示 UIView

ios - 在继续之前等待 NSNotification

python - 如何在 pynotify 中将通知与通用标题合并?

android - ios 闹钟功能受限?

android - 使用 Firebase : Get notification when new message received - Android 的聊天应用

ios - 无效的 iOS bundle

php - 如何通过 PHP 从 Swift 将 UIImage 上传到 MySQL?

javascript - 调用iOS应用程序中嵌入的Javascript

ios - 如果时间过去,UILocalnotification 会直接触发

ios - 使用 IOS 更新 Amazon S3 上的文件名