Swift iOS使用Alamofire请求API后筛选指定标题数据展示
解决方案:过滤指定标题的数据并展示在集合视图
没问题,这事儿其实挺简单的,咱们分几步来搞定——先从返回的所有数据里筛选出你要的那条,再更新集合视图就行:
1. 先定义数据模型(如果还没做的话)
首先得有个符合Decodable的模型来解析API返回的数据,这样处理起来更顺手:
struct Post: Decodable { let userId: Int let id: Int let title: String let body: String }
2. 发起请求并过滤目标数据
用Alamofire拿到全量帖子数据后,直接用filter方法精准筛选出标题匹配的内容,然后更新集合视图的数据源:
// 定义集合视图的数据源数组 var filteredPosts: [Post] = [] // 发起Alamofire请求 AF.request("https://jsonplaceholder.typicode.com/posts") .responseDecodable(of: [Post].self) { response in switch response.result { case .success(let allPosts): // 精确匹配你指定的标题 self.filteredPosts = allPosts.filter { post in post.title == "sunt aut facere repellat provident occaecati excepturi optio reprehenderit" } // 回到主线程更新UI DispatchQueue.main.async { self.collectionView.reloadData() } case .failure(let error): print("请求出错啦: \(error.localizedDescription)") // 这里可以加个弹窗提示用户请求失败 } }
3. 配置集合视图的数据源方法
最后修改集合视图的数据源方法,用过滤后的数组来提供展示数据:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return filteredPosts.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostCell", for: indexPath) as! PostCell let targetPost = filteredPosts[indexPath.item] // 给cell设置标题和其他需要展示的内容 cell.titleLabel.text = targetPost.title cell.bodyLabel.text = targetPost.body return cell }
额外小提示
如果担心标题的大小写、空格差异导致匹配失败,可以改成不区分大小写的匹配逻辑:
self.filteredPosts = allPosts.filter { post in post.title.lowercased() == "sunt aut facere repellat provident occaecati excepturi optio reprehenderit".lowercased() }
内容的提问来源于stack exchange,提问作者user9606220
相关产品推荐
相关产品推荐

