[英]Checking for internet connection or wifi connection with reachabilitySwift
我正在構建一個iOS應用程序,有時需要檢查該應用程序的Internet訪問權限,因此我使用了ReachabilitySwift庫。
經過一些測試,在我看來,該庫僅檢查該設備是否已連接wifi並沒有從路由器提供實際的互聯網連接。
可以說我斷開路由器與互聯網的連接,如果我的iOS設備通過wifi連接到路由器,則可達性告訴我我們已經建立了互聯網連接,而實際上我的路由器沒有互聯網。
我嘗試使用特定主機進行可達性測試,但結果仍然相同
var reachability = Reachability.init(hostname: "google.com");
當wifi連接丟失或實際的互聯網連接丟失時,可到達性庫是否應該提供反饋?
先感謝您。
我在對受VPN保護的網絡進行Web服務調用時遇到了與可達性類似的問題。
var reachability = Reachability.init(hostname: "google.com");
沒有為我工作,因為它在有Wifi連接時返回true。
當對服務器進行虛擬調用時,我使用了Alamofire
響應
func networkIsAvailable(available: (Bool, String?) -> Void) {
var message : String = ""
DispatchQueue.main.async {
HUD.show(.progress)
Alamofire.request(Constants.baseUrl, method: .get, parameters: ["foo": "bar"])
.responseJSON(completionHandler: { (response) in
let error = response.result.error as? NSError
if error?.localizedDescription == networkAlert {
message = networkAlert
available(false, message)
} else if error?.code == cannotConnectServerCode || error?.localizedDescription == cannotConnectServerMessage {
message = cannotConnectServerMessage
available(false, anotherNetworkAlert)
} else {
available(true, nil)
}
})
}
}
在WWDC上,蘋果已經說過很多次了,如果您只需要查看WiFi或手機是否可用,請使用Reachable。 如果您需要查看是否可以連接-則不要使用Reachable; 相反,只需連接並處理錯誤。
Reachable實際上不會檢查它是否可以連接到該基於IP的資源,以及是否可以返回結果。 唯一的方法就是實際嘗試。
在蘋果公司的WWDC網站上尋找與Quinn進行的社交會議,以獲取相同的建議。
在Reachablility.h中,您可以找到一個聲明:
typedef enum : NSInteger {
NotReachable = 0,
ReachableViaWiFi,
ReachableViaWWAN
} NetworkStatus;
然后,在Reachability
類中,您可以找到方法,該方法返回類型:
- (NetworkStatus)currentReachabilityStatus;
因此,使用它。 在您的快速代碼中,您可以這樣做:
if reachability.currentReachabilityStatus == .ReachableViaWiFi {
// Do things...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.