Alamofire: Request timeout is not working

Created on 4 Jun 2016  路  2Comments  路  Source: Alamofire/Alamofire

Hi,

I have set timeoutIntervalForRequest and timeoutIntervalForResource both for NSURLSessionConfiguration but service stop directly when I use below code.

func callService() {
       // var alamoFireManager : Alamofire.Manager?
var alamoFireManager = Alamofire.Manager.sharedInstance
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.timeoutIntervalForRequest = 10 // seconds
        configuration.timeoutIntervalForResource = 10

        alamoFireManager = Alamofire.Manager(configuration: configuration)
        alamoFireManager.request(.GET, RequestCall.API_URL + request, parameters: parameters, encoding: .URL)
            .responseJSON { response in

                if let JSON = response.result.value {
                    print(JSON)
                    callback!((JSON as! NSDictionary))
                }
        }
}

Is any wrong with code? I want timeout when response not retrieve after 10 seconds.

support

Most helpful comment

As soon as your code leaves callService(), there is no longer any reference to your alamoFireManager variable and it is deallocated, cancelling any pending requests you have. You're also redundantly setting alamoFireManager to the sharedInstance and then to a newly allocated instance later on.

What the documentation about custom Managers doesn't state is that you need to keep the manager around somehow. I like to use a static property in a struct:

struct APIManager {
    static let sharedManager: Manager = {
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.timeoutIntervalForRequest = 10        
        return Manager(configuration: configuration)
    }()
}

All 2 comments

As soon as your code leaves callService(), there is no longer any reference to your alamoFireManager variable and it is deallocated, cancelling any pending requests you have. You're also redundantly setting alamoFireManager to the sharedInstance and then to a newly allocated instance later on.

What the documentation about custom Managers doesn't state is that you need to keep the manager around somehow. I like to use a static property in a struct:

struct APIManager {
    static let sharedManager: Manager = {
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.timeoutIntervalForRequest = 10        
        return Manager(configuration: configuration)
    }()
}

@jshier tnx you've saved my life

Was this page helpful?
0 / 5 - 0 ratings

Related issues

filippovdev picture filippovdev  路  3Comments

shivang2902 picture shivang2902  路  3Comments

zhouhao27 picture zhouhao27  路  3Comments

matthijsotterloo picture matthijsotterloo  路  3Comments

Tulleb picture Tulleb  路  3Comments