Developer
Developer

Reputation: 41

Basic auth in swift 5 in iOS

I have referred to many posts with regard to the question I have. Below are the link I have referred,

The basic authentication in swift 5/XCode 12 version is failing. I get the below error in xcode,

2021-07-08 15:28:32.693835+0200 App[43664:810014] Connection 1: encountered error(3:-9816)
2021-07-08 15:33:33.042464+0200 App[43664:821863] Connection 2: received failure notification
2021-07-08 15:33:33.042685+0200 App[43664:821863] Connection 2: failed to connect 3:-9816, reason -1 

Below is the code I am using (I am using urlsession),

var mhUrlRequest = URLRequest(url: mhURL)
let userPasswordData = "username:password".data(using: .utf8)
let base64EncodedCredential = userPasswordData!.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
let authString = "Basic \(base64EncodedCredential)"
mhUrlRequest.setValue(authString, forHTTPHeaderField: "Authorization")

I even tried the below code

let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = ["Authorization" : authString]

But none of these seems to work for me.

Upvotes: 0

Views: 1153

Answers (1)

martosfre
martosfre

Reputation: 874

The conversion of the credentials to base64 is not the better way. Try these code

let url = "your_url"
let usu_pass = "username:password"
var authData = (usu_pass.data(using: .utf8)?.base64EncodedString())!

let url = URL(string:url)
let header = [
    "content-type" : "text/xml",
     "Authorization" : "Basic " + authData
]
        
var request = URLRequest(url: url!)
request.allHTTPHeaderFields = header
request.httpMethod = "POST"
...

Upvotes: 0

Related Questions