I am rewriting my existing Objective-C code (iOS) to Swift and now am facing some issues with the Reachability
class of Apple for checking network availability.
put this code in to your appDelegate for checking reachability .
//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;
}
Simply use like this
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)
}
Try below code
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()
}
For network availability (works in Swift 2):
class func hasConnectivity() -> Bool {
let reachability: Reachability = Reachability.reachabilityForInternetConnection()
let networkStatus: Int = reachability.currentReachabilityStatus().rawValue
return networkStatus != 0
}
For a Wi-Fi connection:
(reachability.currentReachabilityStatus().value == ReachableViaWiFi.value)