Internet connection not available retry option in iOS swift

 Problem:

I want to add retry option in a screen while i call the api method that time network was down. So i want one alert if network not available then retry option wants to be displayed in the screen.

Solution:

Method will be like below

    func showAlert(retryPressed: @escaping() -> Void) {

        let alert = UIAlertController(title: "No Internet Connection", message: "Please check your internet connection and retry", preferredStyle:UIAlertController.Style.alert)

        

        let retryAction = UIAlertAction(title: "Retry" , style: .default) { (action:UIAlertAction!) in

            alert.dismiss(animated: false)

            retryPressed()

        }

        alert.addAction(retryAction)

        

        self.present(alert, animated:true)

    }


You can call the method like below


    func apicall() {

        if InternetConnectionManager.isConnectedToNetwork() {

    } else {

            showAlert(retryPressed: {

                self.apicall()

            })

}

}



Internet connection manager file will be like below


import Foundation

import UIKit

import SystemConfiguration


public class InternetConnectionManager {

    

    

    private init() {

        

    }

    

    public static func isConnectedToNetwork() -> Bool {

        

        var zeroAddress = sockaddr_in()

        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))

        zeroAddress.sin_family = sa_family_t(AF_INET)

        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {

            

            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {

                

                SCNetworkReachabilityCreateWithAddress(nil, $0)

                

            }

            

        }) else {

            

            return false

        }

        var flags = SCNetworkReachabilityFlags()

        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {

            return false

        }

        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0

        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

        return (isReachable && !needsConnection)

    }

    

}

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift