Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire Manager with Swift 2.0 getting Cancelled

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!

like image 540
Graham Avatar asked Sep 17 '15 21:09

Graham


2 Answers

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(...
like image 151
Karson Avatar answered Nov 06 '22 01:11

Karson


Its resolved here in their github issues https://github.com/Alamofire/Alamofire/issues/157

like image 22
raja Avatar answered Nov 06 '22 02:11

raja