如何在ViewController中触发Get Promotion API请求?
在ViewController中触发GetPromotionApiHandler的GET请求
前提确认
你的GetPromotionApiHandler中用到了Handler类型和Promotions模型,需确保这两个已正确定义,示例如下:
// 定义结果枚举 enum Result<T> { case success(T) case failure(Error) } // 别名简化闭包类型 typealias Handler = (Result<[Promotions]>) -> Void // 促销数据模型(需根据API返回字段调整) struct Promotions: Codable { var id: String var title: String // 其他字段... } // 自定义错误类型(对应API中的错误处理) enum CustomError: Error { case custom(message: String) }
在ViewController中调用API请求
你可以在ViewController的生命周期方法(如viewDidLoad)或用户交互事件(如按钮点击)中触发请求,示例代码:
class YourViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 在视图加载完成后触发请求 fetchPromotionData() } // 封装请求方法 private func fetchPromotionData() { GetPromotionApiHandler.sharedInstance.callingPromoAPI { [weak self] result in // 网络请求在子线程执行,更新UI必须切回主线程 DispatchQueue.main.async { switch result { case .success(let promotions): // 请求成功,处理返回的促销数据 print("获取到\(promotions.count)条促销数据") // 示例:更新表格视图或UI组件 // self?.promotionList = promotions // self?.tableView.reloadData() case .failure(let error): // 请求失败,处理错误 if let customErr = error as? CustomError { print("错误提示:\(customErr.message)") // 示例:弹出提示框告知用户 // self?.showErrorAlert(message: customErr.message) } else { print("请求失败:\(error.localizedDescription)") } } } } } // 可选:弹出错误提示的工具方法 private func showErrorAlert(message: String) { let alert = UIAlertController(title: "提示", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "确定", style: .default)) present(alert, animated: true) } }
注意事项
- 主线程更新UI:网络请求默认在子线程执行,所有UI操作必须通过
DispatchQueue.main.async切回主线程,避免界面卡顿或崩溃。 - URL与令牌管理:确保
promotion_url是有效的API地址;硬编码的token在实际项目中应从安全存储(如Keychain)读取,避免敏感信息泄露。 - 错误优化:当前API处理类中错误提示较笼统,可根据具体错误类型(如网络错误、解码失败、状态码异常)返回更精准的提示,提升用户体验。
内容的提问来源于stack exchange,提问作者user15660516
相关产品推荐
相关产品推荐

