我想检查一下我是否在使用 Cocoa Touch 库的 iOS 或使用 Cocoa 库的 macOS 上有互联网连接。

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

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

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

最佳答案

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

迅速

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

2) 通过闭包测试可达性

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")
}

objective-C

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

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

3)更新界面部分
#import "Reachability.h"

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

4) 然后在你可以调用的 View Controller 的 .m 文件中实现这个方法
// 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 文件对之一重命名为其他名称以解决问题。

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

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

10-13 04:30