如何在 iOS 或 macOS 上检查活动的 Internet 连接? [英] How can I check for an active Internet connection on iOS or macOS?

查看:35
本文介绍了如何在 iOS 或 macOS 上检查活动的 Internet 连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Cocoa Touch 库或在 macOS 上使用 Cocoa 库.

I would like to check to see if I have an Internet connection on iOS using the Cocoa Touch libraries or on macOS using the Cocoa libraries.

我想出了一个使用 NSURL 的方法.我这样做的方式似乎有点不可靠(因为即使谷歌有一天可能会失败并且依赖第三方似乎很糟糕),虽然如果谷歌没有回应,我可以检查其他网站的回应,它对我的应用程序来说似乎是浪费和不必要的开销.

I came up with a way to do this using an NSURL. The way I did it seems a bit unreliable (because even Google could one day be down and relying on a third party seems bad), and while I could check to see for a response from some other websites if Google didn't respond, it does seem wasteful and an unnecessary overhead on my application.

- (BOOL) connectedToInternet
{
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
    return ( URLString != NULL ) ? YES : NO;
}

我做错了吗(更不用说 stringWithContentsOfURL 在 iOS 3.0 和 macOS 10.4 中已弃用),如果是这样,有什么更好的方法来实现这一点?

Is what I have done bad, (not to mention stringWithContentsOfURL is deprecated in iOS 3.0 and macOS 10.4) and if so, what is a better way to accomplish this?

推荐答案

重要提示:此检查应始终异步执行.下面的大多数答案都是同步的,所以要小心,否则你会冻结你的应用程序.

Important: This check should always be performed asynchronously. The majority of answers below are synchronous so be careful otherwise you'll freeze up your app.

  1. 通过 CocoaPods 或 Carthage 安装:https://github.com/ashleymills/Reachability.迅速

通过闭包测试可达性

let reachability = Reachability()!

reachability.whenReachable = { reachability in
    if reachability.connection == .wifi {
        print("Reachable via WiFi")
    } else {
        print("Reachable via Cellular")
    }
}

reachability.whenUnreachable = { _ in
    print("Not reachable")
}

do {
    try reachability.startNotifier()
} catch {
    print("Unable to start notifier")
}


目标-C

  1. SystemConfiguration 框架添加到项目中,但不要担心将其包含在任何地方

  1. Add SystemConfiguration framework to the project but don't worry about including it anywhere

将 Tony Million 的 Reachability.hReachability.m 版本添加到项目中(可在此处找到:https://github.com/tonymillion/Reachability)

Add Tony Million's version of Reachability.h and Reachability.m to the project (found here: https://github.com/tonymillion/Reachability)

更新界面部分

#import "Reachability.h"

// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
    Reachability *internetReachableFoo;
}
@end

  • 然后在你可以调用的视图控制器的.m文件中实现这个方法

  • Then implement this method in the .m file of your view controller which you can call

    // Checks if we have an internet connection or not
    - (void)testInternetConnection
    {
        internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
    
        // Internet is reachable
        internetReachableFoo.reachableBlock = ^(Reachability*reach)
        {
            // Update the UI on the main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Yayyy, we have the interwebs!");
            });
        };
    
        // Internet is not reachable
        internetReachableFoo.unreachableBlock = ^(Reachability*reach)
        {
            // Update the UI on the main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Someone broke the internet :(");
            });
        };
    
        [internetReachableFoo startNotifier];
    }
    

  • 重要提示: Reachability 类是项目中最常用的类之一,因此您可能会遇到与其他项目的命名冲突.如果发生这种情况,您必须将一对 Reachability.hReachability.m 文件中的一对重命名为其他名称以解决问题.

    Important Note: The Reachability class is one of the most used classes in projects so you might run into naming conflicts with other projects. If this happens, you'll have to rename one of the pairs of Reachability.h and Reachability.m files to something else to resolve the issue.

    注意:您使用的域无关紧要.它只是测试通往任何域的网关.

    Note: The domain you use doesn't matter. It's just testing for a gateway to any domain.

    这篇关于如何在 iOS 或 macOS 上检查活动的 Internet 连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆