How to Check Internet Connection in Alamofire

Alamofire - detect internet connection

If you're declaring network inside a function it's probably being deallocated as soon as the scope ends.

Make sure you store it in an instance variable.

Attempt to check internet connection on iOS device with Alamofire

create the common class for check the connectivity

import Foundation
import Alamofire

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

and call the function where you need

if !Connectivity.isConnectedToInternet() {
// show Alert
return
}

Checking for Internet Connection continually with Alamofire

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.



Related Topics



Leave a reply



Submit