Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check internet connection in alamofire?

I am using below code for making HTTP request in server.Now I want to know whether it is connected to internet or not. Below is my code

  let request = Alamofire.request(completeURL(domainName: path), method: method, parameters: parameters, encoding: encoding.value, headers: headers)       .responseJSON {           let resstr = NSString(data: $0.data!, encoding: String.Encoding.utf8.rawValue)         print("error is \(resstr)")           if $0.result.isFailure {           self.failure("Network")           print("API FAILED 4")           return         }         guard let result = $0.result.value else {           self.unKnownError()           self.failure("")           print("API FAILED 3")            return         }         self.handleSuccess(JSON(result))     } 
like image 804
TechChain Avatar asked Dec 26 '16 06:12

TechChain


1 Answers

For swift 3.1 and Alamofire 4.4 ,I created a swift class called Connectivity . Use NetworkReachabilityManager class from Alamofire and configure the isConnectedToInternet() method as per your need.

import Foundation import Alamofire  class Connectivity {     class func isConnectedToInternet() -> Bool {         return NetworkReachabilityManager()?.isReachable ?? false     } } 

Usage:

if Connectivity.isConnectedToInternet() {         print("Yes! internet is available.")         // do some tasks..  } 

EDIT: Since swift is encouraging computed properties, you can change the above function like:

import Foundation import Alamofire class Connectivity {     class var isConnectedToInternet:Bool {         return NetworkReachabilityManager()?.isReachable ?? false     } } 

and use it like:

if Connectivity.isConnectedToInternet {         print("Yes! internet is available.")         // do some tasks..  } 
like image 145
abhimuralidharan Avatar answered Sep 17 '22 20:09

abhimuralidharan