In order to authenticate a user into our database, I need to capture their login and password, concatenate both strings and then convert it to base64. I am new to swift programming and have tried several things I googled to no avail.
Here is what I have so far, that doesn’t work:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var userName: UITextField!
@IBOutlet weak var password: UITextField!
@IBAction func loginButton(_ sender: Any) {
let login = (userName.text != nil) && (password.text != nil)
let encoded = login.data(using: .utf8)?.base64EncodedString()
}
}
I keep getting two errors regardless of my approach:
Cannot infer contextual base in reference to member ‘utf8’
and
Value of type ‘Bool’ has no member ‘data’
Any help is appreciated.
3
Answers
What you need is this:
And no force unwrap at all!
You might be looking at something like the following:
To understand where you got wrong
userName.text != nil
means "Is text of username null?" and is a boolean value as in YES/NO ortrue
/false
as in either it is null or it isn’t.let login = (userName.text != nil) && (password.text != nil)
does not combine any string. It basically say "Are both, username and password, non-null?". And again together they both either are non-null or at least one of them is null. So it evaluates to another boolean value as in YES/NO ortrue
/false
.From the code I provided all the safety checks are added and code can exit as doing nothing due to incorrect data. But if you wish to do it unsafely (your app my crash) you can do a one-liner:
It looks like you have a few misunderstandings in your code that are causing these issues.
Firstly, this line of code:
is checking if userName.text and password.text are not nil, returning a boolean value (true or false).
Then, with this line:
you’re trying to convert a Bool to Data and encode it as a base64 string. However, the data(using:) method and base64EncodedString() function expect a String, not a Bool.
Instead, you should be checking if userName.text and password.text are not nil, and if they’re not, concatenate them and convert that to a base64 string. Here’s how you can correct your code: