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

Created on 8 Oct 2014  ·  24Comments  ·  Source: Alamofire/Alamofire

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.

Most helpful comment

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.

All 24 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?

I had the same problem, is there a way to set up a specific session manager for modification instead of modifying the global default one?

@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)
    }
}

@rainypixels , Thanks! I will try it later.

After trying all the solutions provided above, my code still fails with same error. For my case, it's because I made too many requests within same session, which exceed the maximum limit (https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/#//apple_ref/occ/instp/NSURLSessionConfiguration/HTTPMaximumConnectionsPerHost).

Sample code:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPMaximumConnectionsPerHost = 10 // Some arbitrary number that I feel big enough.
let manager = Alamofire.Manager(configuration: configuration)

help me !!!!

Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x78fc41e0 {NSErrorFailingURLKey=myURL, NSErrorFailingURLStringKey=myURL, NSLocalizedDescription=cancelled}

Can you print out the sample request using the debugprint()

my method is:

-(NSURLSessionDataTask *)logingUser:(NSString *)user password:(NSString *)password completion:(void (^)(NSDictionary *results, NSError *error))completion {
NSURLSessionDataTask *task = [self POST:kBASE_URL
parameters:@{@"request" : @"login"}
constructingBodyWithBlock:^(id formData) {
[formData appendPartWithFormData:[user dataUsingEncoding:NSUTF8StringEncoding] name:@"user"];
[formData appendPartWithFormData:[password dataUsingEncoding:NSUTF8StringEncoding] name:@"password"];
}
success:^(NSURLSessionDataTask *task, id responseObject) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(responseObject, nil);
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Received HTTP %ld", (long)httpResponse.statusCode);
completion(nil, nil);
});
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"ERROR: %@", [Utility localize:@"Connection_Error"]);
NSLog(@"ERROR-LOG: %@",error);
completion(nil, error);
});
}];
return task;
}

my Log show:

ERROR: Could not connect to the server

Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x78fc41e0 {NSErrorFailingURLKey=myURL, NSErrorFailingURLStringKey=myURL, NSLocalizedDescription=cancelled}

Are you sure your url is correct, since the address (https://vodafoneplazaapp.vodafone.es:20000/api.php) shows no endpoint.

that is the URL, but managed not find the error in my code

I have the same issue. When I configured the Security Policies:

.PinCertificates(
        certificates: ServerTrustPolicy.certificatesInBundle(),
        validateCertificateChain: true,
        validateHost: true
    )

I got this error:

Error Domain=NSURLErrorDomain Code=-999 "cancelled"

and when I disable the security policies, it works. What could it be the problem? The certificate? The server configuration?

Thanks

Have you configured the App Transport Security (
http://stackoverflow.com/questions/30731785/how-do-i-load-an-http-url-with-app-transport-security-enabled-in-ios-9)
?

2016-01-05 7:58 GMT-08:00 nicopuri [email protected]:

I have the same issue. When I configured the Security Policies:

.PinCertificates(
certificates: ServerTrustPolicy.certificatesInBundle(),
validateCertificateChain: true,
validateHost: true
)

I got this error:

Error Domain=NSURLErrorDomain Code=-999 "cancelled"

and when I disable the security policies, it works. What could it be the
problem? The certificate? The server configuration?

Thanks


Reply to this email directly or view it on GitHub
https://github.com/Alamofire/Alamofire/issues/157#issuecomment-169043226
.

Or, in the Alamofire official page (
https://github.com/Alamofire/Alamofire#app-transport-security)

2016-01-05 8:49 GMT-08:00 Yu Guo [email protected]:

Have you configured the App Transport Security (
http://stackoverflow.com/questions/30731785/how-do-i-load-an-http-url-with-app-transport-security-enabled-in-ios-9)
?

2016-01-05 7:58 GMT-08:00 nicopuri [email protected]:

I have the same issue. When I configured the Security Policies:

.PinCertificates(
certificates: ServerTrustPolicy.certificatesInBundle(),
validateCertificateChain: true,
validateHost: true
)

I got this error:

Error Domain=NSURLErrorDomain Code=-999 "cancelled"

and when I disable the security policies, it works. What could it be the
problem? The certificate? The server configuration?

Thanks


Reply to this email directly or view it on GitHub
https://github.com/Alamofire/Alamofire/issues/157#issuecomment-169043226
.

@guoyu1989 I fixed it! The problem was on the server side. The certificate was signed with SHA-1 instead of SHA256 and the key to generate the Certificate should be 2048, not 4096.

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
}

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)
}

}

@karmaios
I got the same problem, but I resolved it with the method following.

http://stackoverflow.com/questions/33146003/afnetworking-with-request-error-code-999

You need to save the manager so that it lives for the full duration of the request. Save it in a property somewhere.

I created a static instance of Manager in my webapi class.

thanks

dfgerg

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
        )

updated for swift 3 :

            Alamofire.request(escapedString!, method: .get, encoding: JSONEncoding.default)
                .validate(contentType: ["application/json"])
                .responseJSON { response in
                    if response.response?.statusCode == 200 {
                        print("Success with JSON: \(String(describing: response.result.value))")

                    }
                    else {
                        let error = (response.result.value  as? [[String : AnyObject]])
                        print(error!)
                    }
            }

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:

            .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.

Can you help me ? I use proxy server for this request.

  `func sendMessage(){

    var proxyConfiguration = [NSObject: AnyObject]()
    proxyConfiguration[kCFNetworkProxiesHTTPProxy] = "178.32.80.236" as AnyObject
    proxyConfiguration[kCFNetworkProxiesHTTPPort] = 8080 as AnyObject
    proxyConfiguration[kCFNetworkProxiesHTTPEnable] = 1 as AnyObject

    let sessionConfiguration = URLSessionConfiguration.default
    sessionConfiguration.connectionProxyDictionary = proxyConfiguration

    let sessionManager = Alamofire.SessionManager(configuration: sessionConfiguration)

        let parameters: [String: Any] = [

            "chat_id": "-386470116",
            "text": "Заказчик по имени \(String(describing: UserDefaults.standard.string(forKey: "name"))), с номером телефона \(String(describing: UserDefaults.standard.string(forKey: "PhoneNumber"))), забронировал \(number)"
            ]
        sessionManager.request("https://api.telegram.org/bot958395170:AAH4grDEyiA_oXHTCO6RQ-68NpzMi1T0V4w/sendMessage", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
            print(response)
    }
}`
Was this page helpful?
0 / 5 - 0 ratings

Related issues

moritzsternemann picture moritzsternemann  ·  39Comments

tylerlong picture tylerlong  ·  24Comments

kcharwood picture kcharwood  ·  85Comments

mladenny picture mladenny  ·  18Comments

jebeomgyeong picture jebeomgyeong  ·  29Comments