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

Swift视图加载时无法正确获取Quote点赞数的问题求助

修复Quote初始点赞数无法加载的问题

核心问题定位

你的代码存在两个关键问题导致初始点赞数显示为0:

  1. 字段名不匹配:Swift端getLikeCountForQuote方法尝试解析JSON的likeCount字段,但Golang API返回的字段是likes,解析失败后默认返回0。
  2. 线程问题:URLSession的回调在后台线程执行,直接修改@State变量likes可能导致UI无法及时更新(SwiftUI状态变量必须在主线程修改)。

修复步骤

1. 修正JSON字段解析

将Swift代码中解析字段从likeCount改为likes,并确保在主线程执行回调:

private func getLikeCountForQuote(quoteGiven: Quote, completion: @escaping (Int) -> Void) {
    guard let url = URL(string: "omitted for stackoverflow") else {
        DispatchQueue.main.async {
            completion(0)
        }
        return
    }
    
    URLSession.shared.dataTask(with: url) { data, response, error in
        if let data = data,
           let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
           let likeCount = json["likes"] as? Int {
            DispatchQueue.main.async {
                completion(likeCount)
            }
        } else {
            DispatchQueue.main.async {
                completion(0)
            }
        }
    }.resume()
}

2. (可选)使用Codable优化解析

手动解析JSON容易出错,推荐使用Codable协议实现类型安全的API响应解析:
首先定义响应结构体:

struct LikeCountResponse: Codable {
    let id: Int
    let likes: Int
}

然后重构getLikeCountForQuote方法:

private func getLikeCountForQuote(quoteGiven: Quote, completion: @escaping (Int) -> Void) {
    guard let url = URL(string: "omitted for stackoverflow") else {
        DispatchQueue.main.async {
            completion(0)
        }
        return
    }
    
    URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data else {
            DispatchQueue.main.async {
                completion(0)
            }
            return
        }
        
        do {
            let response = try JSONDecoder().decode(LikeCountResponse.self, from: data)
            DispatchQueue.main.async {
                completion(response.likes)
            }
        } catch {
            print("点赞数解析失败: \(error)")
            DispatchQueue.main.async {
                completion(0)
            }
        }
    }.resume()
}

验证修复

修改后,当SingleQuoteView的onAppear触发时,getQuoteLikeCountMethod会正确获取API返回的likes字段值,并在主线程更新likes状态变量,视图会自动刷新显示正确的初始点赞数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 06:37:02