问题:
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 上有互联网连接。
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.我这样做的方式似乎有点不可靠(因为即使有一天谷歌可能会宕机并且依赖第三方似乎很糟糕),虽然如果谷歌没有回应,我可以查看其他一些网站的回应,它对我的应用程序来说似乎是浪费和不必要的开销。
- (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 中已弃用),如果是这样,有什么更好的方法来实现这一点?
解决方案:
参考一: https://stackoom.com/question/4Xv3参考二: How to check for an active Internet connection on iOS or macOS?