1

I am working on my first iOS app and to make network calls I am using Alamofire. It is nice and easy. I implemented Alamofire in separate class, lets call it WebserviceHelper. now I was using this class from all over the application. but now I want to set the timeout.

here is the snippet on how I have made function in WebserviceHelper class.

  static func requestService(methodName: String, method: HTTPMethod, parameters: Parameters, headers: HTTPHeaders? = nil, showLoaderFlag: Bool, viewController: UIViewController, completion: @escaping (_ success: JSON) -> Void) {

    let reachability = Reachability()!

    /*
     checking for internet connection
     */
    if(reachability.connection != .none) {

        /*
         Showing Loader here
         */
        if(showLoaderFlag){
        ViewControllerUtils.customActivityIndicatory(viewController.view, startAnimate: true)
        }

        print("Web Service Url - \(Common.URL+methodName)")
        print("Parameters - \(parameters)")

        /*
         Request configure
         */

        Alamofire.request(Common.URL+methodName, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers) .responseJSON { response in

here you can see it is quiet easy to use it. I have used many ways to set timeout but it is not working for me. this is what I tried. and also this link but nothing really worked for me.

Can you guys help me in setting Timeout using Alamofire.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
A.s.ALI
  • 1,992
  • 3
  • 22
  • 54
  • 2
    Possible duplicate of [Set timeout in Alamofire](https://stackoverflow.com/questions/41803856/set-timeout-in-alamofire) – Pratik Prajapati Feb 01 '19 at 11:47
  • the related link is not working in latest version. Please do not mark it as latest version – A.s.ALI Feb 01 '19 at 11:49
  • Mayur Karmur is correct. I also wanted to add, however, that you shouldn't be using reachability as a precheck for your network calls. Apple specifically recommends against that practice, as reachability is not that exact. – Jon Shier Feb 04 '19 at 22:19
  • Jon Sheir what should I use instead of Reachability – A.s.ALI Feb 05 '19 at 07:08

1 Answers1

3

You should try URLRequest which is working in latest Alamofire as I have already implemented it. See the following code:

guard let url = URL(string: "") else { return }
var urlRequest = URLRequest(url: url)
urlRequest.timeoutInterval = TimeInterval(exactly: 30)!  // Set timeout in request of 30 seconds

Alamofire.request(urlRequest).response { (dataResponse) in

}

I hope this will help you.

piet.t
  • 11,718
  • 21
  • 43
  • 52
Mayur Karmur
  • 2,119
  • 14
  • 35