How to check internet connection in alamofire?

前端 未结 8 1149
醉酒成梦
醉酒成梦 2020-11-30 22:55

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 = Alam         


        
8条回答
  •  心在旅途
    2020-11-30 23:15

    Using RequestAdapter class of alamofire and throw error when no internet connectivity

    class RequestInterceptor : RequestAdapter{
    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
    
        let reachable = NetworkReachabilityManager()?.isReachable ?? false
        if !reachable{
            throw NSError.NoInternet
        }
        var nUrlRequest = urlRequest
        // modify request if needed 
        return nUrlRequest
       }
    }
    
    extension NSError  {
    
    static func createWithLocalizedDesription(withCode code:Int = 204,localizedDescription:String) -> NSError{
        return  NSError(domain: "", code:code, userInfo: [NSLocalizedDescriptionKey : localizedDescription])
    }
    static var NoInternet : NSError {
        return createWithLocalizedDesription(withCode: -1009,localizedDescription:"Please check your internet connection")
    }
    
    }
    

    Now set the adapter to Alamofire Session Manager

    let sessionManager = Alamofire.SessionManager(configuration: configuration)
    
    sessionManager.adapter = RequestInterceptor()
    

    Now each time when You create Alamofire Request, catch the error in DataResponse. This mechanism will act common to all request

提交回复
热议问题