Handle internet connection automatically when internet goes off and comes again in swift 4

468 views Asked by At

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!

2

There are 2 answers

4
esemusa On

Just take a quick look at the documentation: https://github.com/ashleymills/Reachability.swift

override func viewDidLoad() {
    super.viewDidLoad()
    let reachability = try! Reachability()
    NotificationCenter.default.addObserver(self, selector: #selector(checkNetworkStatus(note:)), name: .reachabilityChanged, object: reachability)
    do{
        try reachability.startNotifier()
    }catch{
        print("could not start reachability notifier")
    }
}

@objc func checkNetworkStatus(note: Notification) {
    let reachability = note.object as! Reachability
    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()
        }
    }
}
2
Sagar Sangani On

Try this code:-

import SystemConfiguration

and this function in your class

func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
    if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
        return false
    }

    /* Only Working for WIFI
     let isReachable = flags == .reachable
     let needsConnection = flags == .connectionRequired

     return isReachable && !needsConnection
     */

    // Working for Cellular and WIFI
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    let ret = (isReachable && !needsConnection)

    return ret

}

uses:-

if isConnectedToNetwork(){

        print("Internet Connection Available!")
}
else
{
        print("Internet Connection not Available!")
}