I am using below code for making HTTP request in server.Now I want to know whether it is connected to internet or not. Below is my code
let request = Alam
For swift 3.1 and Alamofire 4.4 ,I created a swift class called Connectivity
. Use NetworkReachabilityManager
class from Alamofire
and configure
the isConnectedToInternet()
method as per your need.
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() -> Bool {
return NetworkReachabilityManager()?.isReachable ?? false
}
}
Usage:
if Connectivity.isConnectedToInternet() {
print("Yes! internet is available.")
// do some tasks..
}
EDIT: Since swift is encouraging computed properties, you can change the above function like:
import Foundation
import Alamofire
class Connectivity {
class var isConnectedToInternet:Bool {
return NetworkReachabilityManager()?.isReachable ?? false
}
}
and use it like:
if Connectivity.isConnectedToInternet {
print("Yes! internet is available.")
// do some tasks..
}
Swift 2.3
Alamofire.request(.POST, url).responseJSON { response in
switch response.result {
case .Success(let json):
// internet works.
case .Failure(let error):
if let err = error as? NSURLError where err == .NotConnectedToInternet {
// no internet connection
} else {
// other failures
}
}
}
Swift 3.0
Alamofire.upload(multipartFormData: { multipartFormData in
}, to: URL, method: .post,headers: nil,
encodingCompletion: { (result) in
switch result {
case .success( _, _, _): break
case .failure(let encodingError ):
print(encodingError)
if let err = encodingError as? URLError, err.code == .notConnectedToInternet {
// no internet connection
print(err)
} else {
// other failures
}
}
})
Using NetworkReachabilityManager
let networkReachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")
func checkForReachability() {
self.networkReachabilityManager?.listener = { status in
print("Network Status: \(status)")
switch status {
case .notReachable:
//Show error here (no internet connection)
case .reachable(_), .unknown:
//Hide error here
}
}
self.networkReachabilityManager?.startListening()
}
//How to Use : Just call below function in required class
if checkForReachability() {
print("connected with network")
}