login example with Basic Athentication for swift?

-1

Hello. I have an api in cakephp with basic Authentication, for android it was easy but I'm not getting an example of a "POST" request passing as "user" and "password" via http:

If someone has an example, thank you.

    
asked by anonymous 27.01.2017 / 19:23

1 answer

0

Maybe this answer from SOen

Swift 3:

let username = "usuario"
let password = "senha"

let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()

//Cria uma requisição
let url = URL(string: "http://www.example.com/pagina")
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

// executa
let urlConnection = NSURLConnection(request: request, delegate: self)

In Swift 2 with NSMutableURLRequest :

let username = "usuario"
let password = "senha"

let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])

//Cria uma requisição
let url = NSURL(string: "http://www.example.com/pagina")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

// Executa
let urlConnection = NSURLConnection(request: request, delegate: self)
    
27.01.2017 / 20:24