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

iOS开发问题:登录后根据ParentID展示关联ChildID数据

iOS端解析并展示家长关联孩子数据的实现方案

嘿,你已经搞定了后端的JSON接口,这步很关键!接下来iOS这边的解析和展示其实没那么复杂,我给你梳理一套完整的实现方案,都是项目里常用的做法:

1. 发起网络请求获取JSON数据

首先我们用系统自带的URLSession来请求你的PHP接口,不用第三方库也能轻松搞定。写个复用性高的请求函数,传入当前登录的ParentID就能拿到对应的数据:

func fetchChildren(for parentID: Int, completion: @escaping ([Child]?, Error?) -> Void) {
    // 替换成你的PHP接口实际地址
    guard let requestURL = URL(string: "https://你的域名/接口路径.php?ParentID=\(parentID)") else {
        let invalidURLError = NSError(domain: "NetworkError", code: -1, userInfo: [NSLocalizedDescriptionKey: "无效的接口地址"])
        completion(nil, invalidURLError)
        return
    }
    
    let task = URLSession.shared.dataTask(with: requestURL) { data, _, error in
        // 先处理网络请求错误
        if let requestError = error {
            completion(nil, requestError)
            return
        }
        
        // 确保返回的数据不为空
        guard let responseData = data else {
            let noDataError = NSError(domain: "DataError", code: -2, userInfo: [NSLocalizedDescriptionKey: "未获取到数据"])
            completion(nil, noDataError)
            return
        }
        
        // 解析JSON(这部分我们后面单独说)
        do {
            let children = try JSONDecoder().decode([Child].self, from: responseData)
            completion(children, nil)
        } catch let decodeError {
            completion(nil, decodeError)
        }
    }
    task.resume()
}

2. 创建数据模型(用Codable协议)

iOS 11+推荐用Codable来解析JSON,比老的JSONSerialization简洁太多。我们创建一个Child模型来对应JSON里的字段:

struct Child: Codable {
    let childId: Int
    let name: String
    let `class`: String // 注意:class是Swift的关键字,所以要加反引号转义
}

你的JSON字段是childId、name、class,和模型属性名完全匹配,所以不需要额外写CodingKeys映射,省了不少代码!

3. 解析并拿到孩子数据数组

在你的ViewController里调用上面的请求函数,记得更新UI必须回到主线程(网络请求是在后台线程执行的):

class ChildrenListViewController: UIViewController {
    // 存储孩子数据的数组
    private var childrenArray: [Child] = []
    // 假设你用UITableView来展示数据
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
        // 这里传入当前登录用户的ParentID,比如10
        loadChildrenData(for: 10)
    }
    
    private func setupTableView() {
        tableView.delegate = self
        tableView.dataSource = self
        // 如果是代码创建cell,记得注册;如果是Storyboard里拖的,确保cell的identifier是"ChildCell"
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "ChildCell")
    }
    
    private func loadChildrenData(for parentID: Int) {
        fetchChildren(for: parentID) { [weak self] children, error in
            DispatchQueue.main.async {
                if let fetchError = error {
                    // 这里可以给用户弹个提示,比如Alert
                    print("获取数据失败:\(fetchError.localizedDescription)")
                    return
                }
                
                guard let fetchedChildren = children else {
                    print("没有找到该家长关联的孩子")
                    return
                }
                
                // 更新数据源并刷新表格
                self?.childrenArray = fetchedChildren
                self?.tableView.reloadData()
            }
        }
    }
}

4. 用UITableView展示数据

实现UITableView的数据源方法,把每个孩子的信息展示出来:

extension ChildrenListViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return childrenArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ChildCell", for: indexPath)
        let currentChild = childrenArray[indexPath.row]
        
        // 自定义cell的展示内容,这里用系统默认cell的textLabel和detailTextLabel举例
        cell.textLabel?.text = currentChild.name
        cell.detailTextLabel?.text = "班级:\(currentChild.class) | 孩子ID:\(currentChild.childId)"
        return cell
    }
    
    // 如果你需要点击cell跳转详情页,可以实现这个方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedChild = childrenArray[indexPath.row]
        print("选中了孩子:\(selectedChild.name),ID:\(selectedChild.childId)")
        // 这里可以跳转到孩子详情页面
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

一些额外注意事项

  • 确保你的PHP接口返回的JSON格式完全正确,比如字段大小写要和模型一致(比如childId不能写成childid或者ChildID)
  • 网络请求要处理无网络的情况,可以自己实现简单的网络状态检测,或者用成熟的第三方库辅助
  • 如果需要更复杂的UI,可以自定义UITableViewCell,把孩子的信息展示得更美观
  • 可以给请求加个loading动画,提升用户等待时的体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:54:33