Alamofire: Error Domain=NSURLErrorDomain Code=-999 "cancelled"

I want to create a custom manager instance and use it:

var configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()

//add the Alamofire default headers to the configuration
configuration.HTTPAdditionalHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders

let manager = Alamofire.Manager(configuration: configuration)

let url = NSURL(string: "http://192.168.0.10/test")

manager.request( NSURLRequest(URL: url) )
    .response{(request, response, _, error) in
        println("\(error)")
    }

Which gives me an error: Error Domain=NSURLErrorDomain Code=-999 “cancelled”

If i try this with the Singleton it works fine:

//let manager = Alamofire.Manager(configuration: configuration)
let manager = Alamofire.Manager.sharedInstance

Shouldn’t the above code work with a custom instanced manager, too?

Thanks in advance.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 25 (1 by maintainers)

Most upvoted comments

The difference here is that the initialized manager is not owned, and is deallocated shortly after it goes out of scope. As a result, any pending tasks are cancelled.

So about this issue how to implementation modified configuration with manager instead of using default configuration with sharedInstance?

@cloud-hot @kohakugawa You just have to ensure that manager is retained. There are lots of ways you can do this. At the simplest level, for example, you could make it a stored property for a custom NetworkManager class:

import Foundation
import Alamofire

class NetworkManager {

    var manager: Manager?

    init() {
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        manager = Alamofire.Manager(configuration: configuration)
    }
}

dfgerg

you can try like this ,but i don’t know why!

class NetworkManager {

var manager: Manager?
static let sharedInstance: Manager = {
    // work
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForRequest = 4
    configuration.timeoutIntervalForResource = 4
    configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders

    return Manager(configuration: configuration)
}()
init() {
    // does not work
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForRequest = 4
    configuration.timeoutIntervalForResource = 4
    configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
    manager =  Alamofire.Manager(configuration: configuration)
}

}

If your certificate is a self-signed certificate, you should set validateCertificateChain to false. You can see this instruction in the Alamofire reference on github.

Follow an example bellow:

let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
            certificates: [secCert!],
            validateCertificateChain: false,
            validateHost: true
        )

I had the same issue with Alamofire and RxSwift. My problem was that I was calling disposedBy() after the subscribe() function to dispose of unused resources.

However, that might have disposed the resource even before the network call succeeded. Removing the disposedBy() call after subscribe() solved the issue for me.

My working code looks like this:

fetchUserAction
            .execute(t: userId)
            .subscribe { event in
                switch event {
                case .success(let user):
                    completion(Result.success(user))
                case .error:
                    completion(Result.error)
                }
            }

Maybe this’ll help someone facing a similar issue.

I had very a stupid problem, maybe this can help someone. I used function that looks like this to get my authenticated operation manager.

func authenticatedOperationManager(block: operationManagerBlock) -> Void {
        self.getAccessTokenWithResponseBlock { (success, response) -> Void in
            if success {
                let accessToken = response as! String

                var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
                defaultHeaders["auth-token"] = "\(accessToken)"

                let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
                configuration.HTTPAdditionalHeaders = defaultHeaders
                configuration.HTTPMaximumConnectionsPerHost = 10
                self.authenticatedOperationManager = Alamofire.Manager(configuration: configuration)

                block(manager: self.authenticatedOperationManager, error: nil)
            }
            else {
                block(manager: nil, error: "\(response)")
            }
        }
    }

As you can see, Manager is retained, MaximumConnectionsPerHost is set to something above 1 or 2 and everything else looks fine. Problem is, with this function I’m practically making a new Manager while the Manager is already working on some request - that’s when the request gets cancelled. I needed to add this block just above let accessToken = …

if (self.authenticatedOperationManager != nil) {
    block(manager: self.authenticatedOperationManager, error: nil)
    return
}