example of login with Basic Athentication for Swift?

Asked

Viewed 103 times

-1

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

if anyone has an example, thank you.

  • Hello Bruno, welcome to Stackoverflow, could you post us an excerpt of the code or a scenario where your question applies? Makes it easier for the community to help you with your problem.

1 answer

0


Perhaps this response 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.