You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Swift购物车APP商店页显示登录用户名及登录逻辑优化咨询

解决方案

1. 登录页空值校验异常修复

问题原因

  • 空值校验逻辑写在账号遍历循环内部,每匹配失败一个账号就触发一次弹窗,导致多次弹窗的异常问题
  • 空值校验未做前置拦截,没必要进入账号匹配逻辑再判断空输入
  • 原注释代码中存在逻辑错误:密码校验误写为和acc.username对比

修复后代码

@IBAction func login(_ sender: Any) {
    // 前置空值校验
    guard let inputName = username.text, !inputName.isEmpty,
          let inputPwd = password.text, !inputPwd.isEmpty else {
        let alert = UIAlertController(title: "提示", message: "请输入用户名和密码", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
        return
    }
    // 账号匹配逻辑
    var loginSuccess = false
    for acc in userList {
        if inputName == acc.username && inputPwd == acc.password {
            currentUser = inputName
            do {
                try context.save()
            } catch {
                print("数据保存失败: \(error.localizedDescription)")
            }
            loginSuccess = true
            break // 匹配成功直接跳出循环,避免多余遍历
        }
    }
    // 统一处理登录结果
    if loginSuccess {
        performSegue(withIdentifier: "DisplayShop1", sender: nil)
    } else {
        let alert = UIAlertController(title: "提示", message: "用户名或密码错误", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
}

2. 列表页顶部用户名显示修复

问题原因

原代码直接将用户数组userList拼接到展示字符串中,输出的是数组对象的描述信息,不是具体的用户名。

修复后代码(替换ListingShopVC的viewDidLoad相关逻辑)

override func viewDidLoad() {
    super.viewDidLoad()
    fetch()
    tableView.delegate = self
    tableView.dataSource = self
    extracted()
    // 直接使用全局存储的登录用户名
    usernameloggedin.text = "Welcome \(currentUser)"
    // 匹配当前登录用户的积分信息展示
    if let currentUserInfo = userList.first(where: { $0.username == currentUser }) {
        // 替换credits为你User实体中对应的积分属性名
        creditsdisplay.text = "You have \(currentUserInfo.credits) credits"
    } else {
        creditsdisplay.text = "You have 0 credits"
    }
}

可选优化建议

  • 如果不想使用全局变量currentUser,可以在LoginVC的prepareForSegue方法中将登录用户名传递给ListingShopVC,避免全局变量污染
  • 替换代码中所有try!写法为do-catch捕获异常,避免运行时崩溃

内容的提问来源于stack exchange,提问作者KAKEN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:24:09