Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

ios - 如何在iOS或macOS上检查活动的Internet连接?(How to check for an active Internet connection on iOS or macOS?)

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.

(我想检查一下我是否在使用Cocoa Touch库的iOS上或在使用Cocoa库的macOS上建立了Internet连接。)

I came up with a way to do this using an NSURL .

(我想出了一种使用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.

(我这样做的方式似乎有点不可靠(因为即使Google可能有一天会倒闭,依赖第三方也似乎很糟糕),而且我可以检查一下是否有其他网站的响应(如果Google没有响应),确实看起来很浪费,而且对我的应用程序来说也没有不必要的开销。)

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

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?

(我做的不stringWithContentsOfURL (更不用说在iOS 3.0和macOS 10.4中不推荐使用stringWithContentsOfURL ),如果是的话,有什么更好的方法来做到这一点?)

  ask by Brock Woolf translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(以下大多数答案是同步的,因此请小心,否则将冻结您的应用程序。)


Swift (迅速)

1) Install via CocoaPods or Carthage: https://github.com/ashleymills/Reachability.swift

(1)通过CocoaPods或迦太基安装: https : //github.com/ashleymills/Reachability.swift)

2) Test reachability via closures

(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) Add SystemConfiguration framework to the project but don't worry about including it anywhere

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

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

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

3) Update the interface section

(3)更新界面部分)

#import "Reachability.h"

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

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

(4)然后在您可以调用的视图控制器的.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];
}

Important Note: The Reachability class is one of the most used classes in projects so you might run into naming conflicts with other projects.

(重要说明: Reachability类是项目中最常用的类之一,因此您可能会遇到与其他项目的命名冲突。)

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.

(如果发生这种情况,则必须将Reachability.hReachability.m文件对中的一个重命名为其他名称才能解决此问题。)

Note: The domain you use doesn't matter.

(注意:您使用的域无关紧要。)

It's just testing for a gateway to any domain.

(它只是测试通往任何域的网关。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...