ios 如何在swift中将两个字符串连接成一个编码的base64字符串?

disbfnqx  于 2023-07-01  发布在  iOS
关注(0)|答案(3)|浏览(97)

为了验证数据库中的用户,我需要捕获他们的登录名和密码,连接这两个字符串,然后将其转换为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”
任何帮助都很感激。

r7knjye2

r7knjye21#

看起来您的代码中有一些误解导致了这些问题。
首先,这行代码:

let login = (userName.text != nil) && (password.text != nil)

检查userName.text和password.text是否不为nil,返回一个布尔值(true或false)。
然后,使用这一行:

let encoded = login.data(using: .utf8)?.base64EncodedString()

你正在尝试将Bool转换为Data并将其编码为base64字符串。但是,data(using:)方法和base64EncodedString()函数需要的是String,而不是Bool。
相反,您应该检查userName.text和password.text是否不为nil,如果不是,则将它们连接起来并将其转换为base64字符串。以下是如何纠正代码:

@IBAction func loginButton(_ sender: Any) {
        guard let login = userName.text, let pwd = password.text else {
            print("Username or password is missing")
            return
        }

        let combined = login + pwd

        let data = Data(combined.utf8)

        let encoded = data.base64EncodedString()

        print(encoded)
  }
ymzxtsji

ymzxtsji2#

你需要的是:

let encoded = 
  [userName, password]
    .compactMap(\.text) // Extract the text if there is not nil
    .filter { !$0.isEmpty } // filter out empty strings
    .joined(separator: " ") // concatenate them using a space (you can use any separator you like or just pass in an empty string)
    .data(using: .utf8)? // make it data
    .base64EncodedString() // make it base 64

而且根本没有力量解开!

guz6ccqo

guz6ccqo3#

您可能会看到以下内容:

@IBAction func loginButton(_ sender: Any) {
    guard let name = userName?.text else { return } // No user name
    guard let password = password?.text else { return } // No password
    
    let combinedText = name + password
//    let combinedText = [name, password].joined(separator: "&") Use this if you need a separator between the two strings
    
    guard let encoded = combinedText.data(using: .utf8) else { return } // Could not encode to UTF8 for some reason
    let base64Encoded = encoded.base64EncodedString()
}

去理解你错在哪里
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字符串数据
从我提供的代码中,添加了所有安全检查,并且代码可以由于不正确的数据而退出。但如果你想不安全地这样做(你的应用程序我崩溃),你可以做一行程序:

let base64Encoded = (userName.text! + password.text!).data(using: .utf8)!.base64EncodedString()

相关问题