Использование класса достижимости Apple в Swift
Я переписываю существующий код Objective-C (iOS) в Swift и теперь сталкиваюсь с некоторыми проблемами с классом Reachability
Apple для проверки доступности сети... В моем существующем коде я использую следующее для достижения этого.
var reachability: Reachability = Reachability.reachabilityForInternetConnection()
var internetStatus:NetworkStatus = reachability.currentReachabilityStatus()
if (internetStatus != NotReachable) {
//my web-dependent code
}
else {
//There-is-no-connection warning
}
И я получаю эту ошибку: network status is not convertible to string
в этой строке:
if (internetStatus != NotReachable)
Есть ли способ или класс для получения статуса сети?
Мне нужны эти три условия:
NotReachable: Obviously, there’s no Internet connection
ReachableViaWiFi: Wi-Fi connection
ReachableViaWWAN: 3G or 4G connection
Ответы
Ответ 1
Доступность сети (работает в Swift 2):
class func hasConnectivity() -> Bool {
let reachability: Reachability = Reachability.reachabilityForInternetConnection()
let networkStatus: Int = reachability.currentReachabilityStatus().rawValue
return networkStatus != 0
}
Для подключения Wi-Fi:
(reachability.currentReachabilityStatus().value == ReachableViaWiFi.value)
Ответ 2
Попробуйте ввести код
let connected: Bool = Reachability.reachabilityForInternetConnection().isReachable()
if connected == true {
println("Internet connection OK")
}
else
{
println("Internet connection FAILED")
var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
Ответ 3
введите этот код в свой appDelegate для проверки доступности.
//MARK: reachability class
func checkNetworkStatus() -> Bool {
let reachability: Reachability = Reachability.reachabilityForInternetConnection()
let networkStatus = reachability.currentReachabilityStatus().rawValue;
var isAvailable = false;
switch networkStatus {
case (NotReachable.rawValue):
isAvailable = false;
break;
case (ReachableViaWiFi.rawValue):
isAvailable = true;
break;
case (ReachableViaWWAN.rawValue):
isAvailable = true;
break;
default:
isAvailable = false;
break;
}
return isAvailable;
}
Ответ 4
Просто используйте
do {
let reachability: Reachability = try Reachability.reachabilityForInternetConnection()
switch reachability.currentReachabilityStatus{
case .ReachableViaWiFi:
print("Connected With wifi")
case .ReachableViaWWAN:
print("Connected With Cellular network(3G/4G)")
case .NotReachable:
print("Not Connected")
}
}
catch let error as NSError{
print(error.debugDescription)
}