I am using reachability swift to handle internet conditions in swift 4.I can successfully detect if internet is working or not ,if internet is available my code navigates to the desired page successfully but if internet is not available it shows alert message that there is no internet connection available.
override func viewDidLoad() {
super.viewDidLoad()
do{
reachability = try Reachability()
try reachability?.startNotifier()
}catch{
print("could not start reachability notifier")
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.checkNetworkStatus()
}
func checkNetworkStatus() {
let alert = UIAlertController(title: "", message: "无网络连接", preferredStyle: .alert)
if reachability?.isReachable == true {
alert.dismiss(animated: true, completion:nil)
queryObj()
} else {
alert.addAction(UIAlertAction(title: "好", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
default :
print("default")
}}))
self.present(alert, animated: true, completion: nil)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when){
self.checkNetworkStatus()
}
}
}
func queryObj(){
Alamofire.request(self.base_url ).responseJSON { response in
if
let result = response.result.value
{
let JSON = result as! NSDictionary
let server_status = JSON.object(forKey: "code") as? String
if server_status == "200"{
let preResult = JSON.object(forKey: "result") as! NSDictionary
let result1 = preResult.object(forKey: "iconimage") as! String
let supportViewController = self.storyboard!.instantiateViewController(withIdentifier: "support") as! SupportViewController
supportViewController.supportURL = result1
self.present(supportViewController, animated: false, completion: nil)
return
}else{
let mainViewController = self.storyboard!.instantiateViewController(withIdentifier: "nav")
self.present(mainViewController, animated: false, completion: nil)
}
}else{
self.queryObj()
}
}
}
- Doubt
Suppose if initially ,user has put mobile data off ...this code will show that "there is no internet connection" but even if the user puts on the internet it doesn't push to the other page and hits my url which supposedly it should do.
How can I handle this situation?
I want the code to work instantly when user puts the mobile data on.Please help me in this small roblem. Any help or guidance would be appreciable.Thanks in advance!
Just take a quick look at the documentation: https://github.com/ashleymills/Reachability.swift