Swift 2 https with BASIC Authentication

In order to access a remote URL programatically in Swift 2…

    func getData() {

let username = “myUsername”

let password = “myPassword”

let url = NSURL(string:  “https://www.example.com/path/list”)!

let credentials = NSURLCredential(user: username, password: password, persistence: NSURLCredentialPersistence.ForSession)

let protectionSpace = NSURLProtectionSpace(host: url.host!, port: 443, `protocol`: url.scheme, realm: “myRealm”, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)

let credentialStorage = NSURLCredentialStorage.sharedCredentialStorage()

credentialStorage.setCredential(credentials, forProtectionSpace: protectionSpace)

let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()

sessionConfiguration.URLCredentialStorage = credentialStorage

let session = NSURLSession(configuration: sessionConfiguration)

let task = session.dataTaskWithURL(url, completionHandler: getDataCompletionHandler)

task.resume()

}

func getDataCompletionHandler(data: NSData?, response: NSURLResponse?, error: NSError?) {

if error != nil {

print(“Error: \(error)”)

} else {

if let httpResponse = response as? NSHTTPURLResponse {

print( “Status Code: \(httpResponse.statusCode)”)

}

print(“Data: \(data)”)

}