Currently i'm playing around with IOS, XCode and Swift and i'm trying to call a local Rest Service that uses HTTP Basic Auth.

As a result of my request i get the following: Found: error - unauthorized Found: reason - password required

Here is my function that is doing the request

func connect(url: String) -> Bool {

    let url: NSURL = NSURL(string: url);
    let login:String = "admin";
    let password:String = "test123";

    var defaultCredentials: NSURLCredential = NSURLCredential(user: login, password: password, persistence: NSURLCredentialPersistence.ForSession);

    let host: String =;
    let port: Int = url.port;
    let prot: String = url.scheme;

    println("set following vars \(host) + \(port) + \(prot)");

    var protectionSpace: NSURLProtectionSpace = NSURLProtectionSpace(host: host,port: port,`protocol`: prot,realm: nil,authenticationMethod: NSURLAuthenticationMethodHTTPBasic);

    var credentialStorage: NSURLCredentialStorage = NSURLCredentialStorage.sharedCredentialStorage();
    credentialStorage.setCredential(defaultCredentials, forProtectionSpace: protectionSpace);

    var sessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration();
    sessionConfiguration.URLCredentialStorage = credentialStorage;

    let session: NSURLSession = NSURLSession(configuration: sessionConfiguration); //NSURLSession.sharedSession()


    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
        println("Task completed")
        if((error) != nil) {
            // If there is an error in the web request, print it to the console
        var err: NSError?
        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
        if(err != nil) {
            // If there is an error parsing JSON, print it to the console
            println("JSON Error \(err!.localizedDescription)")



    return true

Could anybody please give me a hint. THX a lot.

Related posts

Recent Viewed