简体   繁体   中英

Updated the almofire timeoutIntervalForRequest for each API in swift?

In our project we are using the network manager to handle all the requests and responses using Alamofire. In alamofire we are the default time out internal as 30. But we need to change the “timeoutIntervalForRequest” for some request as 50,60 etc.

private var manager : SessionManager?

    func sessionManager() -> SessionManager {
        if let manage = self.manager {
            return manage
        }
        else {
            let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = 30
            self.manager = SessionManager(configuration: configuration, delegate: CustomSessionDelegate())
            return self.manager!
        }
    }

I have added the param timeinterval and set default value in it.

func sessionManager(timeoutInterval:Double = 30) -> SessionManager {
//passed the param 
configuration.timeoutIntervalForRequest = timeoutInterval
}

But the time interval value not updated. My question is how to update the timeout interval for SessionManager for each request with this function. We can achieve it using the timeout interval for every API but I want it above common funtion.

You can override the function as:

func sessionManager(timeInterval : Double) -> SessionManager {
        if let manage = self.manager {
            return manage
        }
        else {
            let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = timeInterval
            self.manager = SessionManager(configuration: configuration, delegate: CustomSessionDelegate())
            return self.manager!
        }
    }

It will work fine in every Api Call

Instead of setting the timeoutIntervalForRequest, why not set the timeoutInterval in URLRequest object and than pass that request into Alamofire function.

    let request = NSMutableURLRequest(url: URL(string: "")!)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.timeoutInterval = 50 
Alamofire.request(request as! URLRequestConvertible).responseJSON {
        response in
        // do whatever you want here
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM