Swift: Add basic HTTPAuth to NSURLSession

First you need to make sure that you use a different NSURLSessionConfiguration, where you will modify the headers.
The HTTP Auth needs to be like “Basic: base64 string”, the base64 string being the encoding of username:password.

let userPasswordString = "\(email):\(password)"
            let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
            let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(nil)
            let authString = "Basic \(base64EncodedCredential)"
            sessionConfiguration.HTTPAdditionalHeaders = ["Authorization" : authString]

Leave a Reply