I have a Swift 2.0 ApiManager class using Alamofire 2.0 with the following init:
var manager:Manager
init() {
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["Authorization"] = "Bearer \(UserAccount.sharedInstance.token)"
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders
manager = Alamofire.Manager(configuration: configuration)
}
Example function:
func getMe(completion:(jsonObject: NSDictionary) -> ()) {
manager.request(.GET, Constants.apiURL + "me").responseJSON { request, response, result in
print(self.manager) //THIS LINE FIXES IT
switch result {
case .Success(let json):
completion(jsonObject: json as! NSDictionary)
case .Failure(let data, let error):
print("Error: \(__FUNCTION__)\n", data, error)
}
}
}
The error I receive:
Error Domain=NSURLErrorDomain Code=-999 "cancelled"
It appears the request gets cancelled because the manager is being deallocated. Adding the print statement prevents the manager from being deallocated and it works perfect then. But I'm trying to find a better solution.
Any help would be appreciated!
I was running to this same issue, I used this to fix it
class Session {
static let sharedInstance = Session()
private var manager : Manager?
func ApiManager()->Manager{
if let m = self.manager{
return m
}else{
let defaultHeaders = ["X-Version":"Some header"]
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders
let tempmanager = Alamofire.Manager(configuration: configuration)
self.manager = tempmanager
return self.manager!
}
}
}
then I called it with
Session.sharedInstance.ApiManager().request(...
Its resolved here in their github issues https://github.com/Alamofire/Alamofire/issues/157
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