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

使用Rest Api从WordPress获取数据时缺失最后一篇帖子求助

问题:WordPress API拉取数据缺失最后一篇帖子

我用Xcode开发App,通过REST API从我的WordPress网站获取数据,其他功能均正常,但网站共有15篇帖子,App中仅能看到14篇,最后一篇帖子缺失。

相关代码

1. API请求代码

let url = URL(string: "https://www.pbkalam.com/wp-json/wp/v2/posts/?page=\(page)\(sortBy)" )!
print(url)
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    
    guard let data = data else {return}
    
    do {
        let postsData = try JSONDecoder().decode([Post].self, from: data)
        completionHandler(postsData)
        DispatchQueue.main.async {
            self.collectionView.isUserInteractionEnabled = true
            self.collectionView.reloadData()
            SVProgressHUD.dismiss()
            
            }
    }
    catch {
        let error = error
        print(String(describing: error))
        
     }
 }
task.resume()

2. 列表预加载代码

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if indexPath.item == self.newsData.count - 1 {  //numberofitem count
        DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
            self.page += 1
            self.updateNextSet()
            SVProgressHUD.show()
        }
    }
}

3. 单元格配置代码

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postcell", for: indexPath) as! ViewCell
cell.setup(with: newsData[indexPath.row-(indexPath.row/4)])
cell.backgroundColor = .white
return cell

已尝试的无效修改

修改了预加载判断条件,但没有效果:

if indexPath.item == self.newsData.count {  //numberofitem count
    DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
        self.page += 1
        self.updateNextSet()

排查方向与解决方案

1. 修正单元格数据索引错误

单元格配置代码里的newsData[indexPath.row-(indexPath.row/4)]逻辑存在问题:

  • 当indexPath.row为4时,4/4=1,索引变为4-1=3,重复加载了第3条数据;
  • 每4条数据就会重复一条,直接导致最后一条数据无法被正确展示。

直接使用indexPath.row作为数组索引即可,修改后代码:

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postcell", for: indexPath) as! ViewCell
cell.setup(with: newsData[indexPath.row])
cell.backgroundColor = .white
return cell

2. 验证API分页数据完整性

WordPress REST API默认每页返回10条数据,15条数据会分为两页(10条+5条)。可以在API请求的completionHandler里打印postsData.count,确认第二页是否确实返回了5条数据,同时检查newsData数组是否正确追加了新数据(而非替换)。

3. 确认预加载逻辑触发时机

原预加载逻辑在显示到最后一条数据时请求下一页,若总数据为15条,触发第三页请求时会返回空数据,这不会影响现有数据展示,但如果数据拼接逻辑有误(比如未追加而是替换),也会导致数据缺失,需确保newsData是通过append(contentsOf:)方式添加新数据。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:05:18