問題:
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?