user10692948
user10692948

Reputation:

Checking for Internet Connection continually with Alamofire

My app is based on a TableView that download some data from a server using Alamofire. So because it's necessary to have an internet connection to use my app I want to check it continuously. I find a solution creating this class:

class Connectivity {
class func isConnectedToInternet() -> Bool {
    return NetworkReachabilityManager()!.isReachable
}

}

And I add these lines of code in every method to check for Internet connection

if !Connectivity.isConnectedToInternet() {

        print("No internet connection")
        } else {
            print("connected")
        }

It works but I don't think that this is the right method to check continuously for the connection. I think that I've to implement some observer using notificationCenter from appDelegate but I don't know how to do it...

Upvotes: 1

Views: 2427

Answers (2)

Andrea Culot
Andrea Culot

Reputation: 112

As Jon Shier and Matt say you shouldn't do this. In fact if you are using Alamofire to download an image I suggest you to using instead AlamofireImage and use this code:

let url = URL(string: yourUrl)!

        cell.yourImage.af_setImage(
            withURL: url,
            placeholderImage: placeholderImage,
            imageTransition: .crossDissolve(0.2),
            runImageTransitionIfCached: false,
            completion: { response in
                if response.result.isSuccess {
                    self.dismissLabel()
                } else if response.error?._code == NSURLErrorNotConnectedToInternet{
                    self.showLabel()
                }
        })

So basically you can show a label "No internet Connection" when AlamofireImage retrieves a connection error while downloading your image. Instead if it succeeded to download it you dismiss the label.

Upvotes: 0

Jon Shier
Jon Shier

Reputation: 12770

Do not do this! Apple has said for years that you should never use a reachability check as a prerequisite for making a request. Instead you should make the request and deal with the failure, using reachability to possibly retry the request when it detects connectivity has been reestablished. Reachability is not 100% reliable and is also now deprecated by the NWPathMonitor class.

Upvotes: 2

Related Questions