Hi I'm trying to create a custom SessionManager in Alamofire in order to change the default timeoutIntervalForRequest value. I'm using the code below:
let configuration=URLSessionConfiguration.default
configuration.timeoutIntervalForRequest=20
let sessionManager=Alamofire.SessionManager(configuration:configuration)
sessionManager.request("my url", method: .post, parameters: params, encoding: JSONEncoding.default, headers: header)
.responseJSON(completionHandler: { (response) in
if response.result.isSuccess{
//here goes the rest of my code
}
}
else{
//here goes the connection error part
}
})
The problem is I'm always getting the error part and when I print the response in error part, it looks like this:
finished with error - code: -999
FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled"
as if my request immediately cancels. If I change the sessionManager to Alamofire that is the default manager, it works fine but I need to change timeoutIntervalForRequest value. I'm using Xcode 9.3 and swift 4 and Alamofire 4.7.2 . Any Suggestions?
I found a solution in Alamofire repository issues
jshier commented on Oct 10, 2016
An unexpected error -999 almost always means your SessionManager was deallocated, cancelling any ongoing requests. I suggest you create a singleton value for your custom SessionManager, or perhaps just reevaluate if you really need one.
if you create a singleton value for your object it remains in memory and prevent from deallocate
and another thing that i avoid is to name your variables diffrent, a sessionManager is in Alamofire and your variable is also called sessionManager.
import Alamofire
class Networking {
public static let sharedManager: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest=20
let manager = Alamofire.SessionManager(configuration: configuration, delegate: SessionManager.default.delegate)
return manager
}()
}
import Alamofire
class Networking {
static let APIManager: Session = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 20
let delegate = Session.default.delegate
let manager = Session.init(configuration: configuration,
delegate: delegate,
startRequestsImmediately: true,
cachedResponseHandler: nil)
return manager
}()
}
I solved this issue by adding additional headers to my custom Alamofire session manager:
static let sessionManager: Alamofire.SessionManager = {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 10
config.timeoutIntervalForResource = 10
config.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return Alamofire.SessionManager(configuration: config)
}()
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With