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

如何在选项弹窗内添加成功或错误提示弹窗?iOS开发问题

解决删除账户后弹窗崩溃的问题

问题根源

  • API请求的回调闭包默认运行在后台线程,而present弹窗这类UI操作必须在主线程执行,直接调用会触发线程错误导致崩溃。
  • errorAlert方法创建的弹窗未添加任何操作按钮,既不符合UI规范,也可能引发视图层级异常。

修正方案

1. 完善弹窗方法(确保主线程执行+添加关闭按钮)

// 错误提示弹窗
func errorAlert() {
    DispatchQueue.main.async {
        let dialogMessage = UIAlertController(title: "Error", message: "Failed to delete account", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        dialogMessage.addAction(okAction)
        self.present(dialogMessage, animated: true, completion: nil)
    }
}

// 成功提示弹窗
func successAlert() {
    DispatchQueue.main.async {
        let successDialog = UIAlertController(title: "Success", message: "Account deleted successfully", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { _ in
            // 可在此添加删除成功后的后续操作,例如跳转登录页
        }
        successDialog.addAction(okAction)
        self.present(successDialog, animated: true, completion: nil)
    }
}

2. 修正API回调中的弹窗调用

let okayAction = UIAlertAction(title: "OK", style: .default) { (action) in
    RestAPIManager.sharedInstance.deleteAccount(userID: userID){
        (json, error) in
        if json != JSON.null {
            print(json)
            if json["success"] == true {
                self.successAlert()
            } else {
               self.errorAlert()
            }
        } else {
           // 处理网络请求失败的情况
           self.errorAlert()
        }
    }
}

3. 额外优化:避免强制解包崩溃

原代码中let userID = prefs.value(forKey: "userId") as! String使用强制解包,若userId不存在会直接崩溃,建议替换为可选绑定:

guard let userID = prefs.value(forKey: "userId") as? String else {
    let alert = UIAlertController(title: "Error", message: "User not logged in", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default))
    self.present(alert, animated: true)
    return
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:25:39