为了验证数据库中的用户,我需要捕获他们的登录名和密码,连接这两个字符串,然后将其转换为base64。我是Swift编程的新手,尝试过几种我在谷歌上搜索过的东西都无济于事。
以下是我目前为止所做的,这不起作用:
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()
}
}
不管我的方法如何,我总是得到两个错误:
无法推断引用成员“utf8”的上下文基
和
类型“Bool”的值没有成员“data”
任何帮助都很感激。
3条答案
按热度按时间r7knjye21#
看起来您的代码中有一些误解导致了这些问题。
首先,这行代码:
检查userName.text和password.text是否不为nil,返回一个布尔值(true或false)。
然后,使用这一行:
你正在尝试将Bool转换为Data并将其编码为base64字符串。但是,data(using:)方法和base64EncodedString()函数需要的是String,而不是Bool。
相反,您应该检查userName.text和password.text是否不为nil,如果不是,则将它们连接起来并将其转换为base64字符串。以下是如何纠正代码:
ymzxtsji2#
你需要的是:
而且根本没有力量解开!
guz6ccqo3#
您可能会看到以下内容:
去理解你错在哪里
1.编写类似
userName.text != nil
的内容意味着“用户名的文本是否为null?“并且是一个布尔值,如YES/NO或true
/false
,如它是null或它不是。1.那么
let login = (userName.text != nil) && (password.text != nil)
不会合并任何字符串。它基本上是说“用户名和密码都是非空的吗?并且再次一起,它们两者都是非空的或者它们中的至少一个是空的。因此,它计算为另一个布尔值,如YES/NO或true
/false
。1.然后尝试将其编码为base64编码的UTF8字符串数据
从我提供的代码中,添加了所有安全检查,并且代码可以由于不正确的数据而退出。但如果你想不安全地这样做(你的应用程序我崩溃),你可以做一行程序: