tableviewController 分页两次从服务器检索我的数据,但并非所有数据都从服务器检索

如何解决tableviewController 分页两次从服务器检索我的数据,但并非所有数据都从服务器检索

我有一个包含 3 个单元格的 tableviewController,一个用于从服务器获取图像和文本,第二个用于仅获取文本,第三个用于使用活动指示器实现分页,如下图所示 the 3 cells image


这是分页的响应:

{
    "statusCode": 200,"message": "Success","data": {
        "result": [
            {
                "id": 28,"profileId": 12,"creatorId": 8,"postText": "اهلا وسهلا","commentsCount": 0,"interactionsCount": 0,"createdAt": "2021-03-06T15:45:24.756Z","updatedAt": "2021-03-06T15:45:24.756Z","profile": {
                    "id": 12,"logo": "https://onebusinessqrcode.s3.us-east-2.amazonaws.com/b562b93c-e278-5027-b615-edd399878c1a.jpg","name": "abdallah eslah","category": "Ecommerce","subCategory": "ElectronicMarket"
                },"creator": {
                    "id": 8,"image": "https://onebusinessqrcode.s3.us-east-2.amazonaws.com/0d362ee3-78e3-584a-8c34-6a91afa9dbda.png","email": "abdallaheslah@yahoo.com","mobile": "201094339599"
                },"media": [
                    {
                        "id": 396,"postId": 28,"media": "https://onebusinessqrcode.s3.us-east-2.amazonaws.com/2ad0ce30-a387-5c73-846a-eb414108fb72.jpg","createdAt": "2021-03-06T15:45:25.438Z","updatedAt": "2021-03-06T15:45:25.438Z"
                    }
                ]
            },{
                "id": 5,"postText": "My new product","commentsCount": 2,"createdAt": "2021-03-01T07:13:39.400Z","updatedAt": "2021-03-01T07:17:15.905Z","media": [
                    {
                        "id": 395,"postId": 5,"media": "https://onebusinessqrcode.s3.us-east-2.amazonaws.com/74c28cd0-47be-5053-85ca-c887cc36c781.jpg","createdAt": "2021-03-01T07:13:40.377Z","updatedAt": "2021-03-01T07:13:40.377Z"
                    }
                ]
            }
        ],"thisPage": 1,"allPages": 1,"count": 2
    }
}

所以我在下面的请求中使用它们来获取数据并实现分页:


//Used Variables in the request 
 var posts = [Posts]()
 var pictures = [UIImage]()

//Pagination Vars
 var allPages = 1
 var thisPage = 1

override func viewDidLoad() {
  super.viewDidLoad()
self.refreshControl = UIRefreshControl()
    self.refreshControl?.addTarget(self,action: #selector(refreshData),for: .valueChanged)
    self.refreshData()
 }

// MARK: - List All Posts
    @objc func refreshData(){
        thisPage = 1
        loadPosts(page: 1,refresh: true)
        
    }



@objc func loadPosts(page: Int,refresh: Bool = false) {
        
        if refresh {
   
            refreshControl?.beginRefreshing()
        }
        let profileId = UserDefaults.standard.value(forKey: "id") as? Int ?? 0
        
        var urlBuilder?.queryItems = [
        URLQueryItem(name: "profileId",value:"\(profileId)"),URLQueryItem(name: "page",value:"\(page)")
    ]
        
        guard let url = urlBuilder?.url else { return }
        
        var request = URLRequest(url: url)
        
        let token = UserDefaults.standard.value(forKey: "token") as? String ?? ""
        
        request.httpMethod = "GET"
        
        request.setValue(token,forHTTPHeaderField: "x-auth-token")
        
        // send request
        URLSession.shared.dataTask(with: request) { (data,response,error) in
            DispatchQueue.main.async {
                
                if refresh {
                    self.posts.removeAll()
                    self.refreshControl?.endRefreshing()
                }
                
                // error occured
                if error != nil {
                    Helper().showAlert(title: "Server Error",message: error!.localizedDescription,in: self)
                    return
                }
                
                do {
                    // access data - safe mode
                    guard let data = data else {
                        Helper().showAlert(title: "Data Error",in: self)
                        return
                    }
                    
                    // converting data to JSON
                    let json = try JSONSerialization.jsonObject(with: data,options: .allowFragments) as? NSDictionary
                    
                    guard let parsedJSON = json else {
                        print("Parsing Error")
                        return
                    }
                    
                    if let data = parsedJSON["data"] as? NSDictionary {
                        self.allPages = data["allPages"] as? Int ?? 1

                        let object = Posts()

                        object.allPages = self.allPages
                      
                        if let posts = data["result"] as? [NSDictionary] {
                            for item in posts {
                                
                                
                                if let interactionsCount = item["interactionsCount"] as? Int {
                                    
                                    object.interactionsCount = interactionsCount
                                    
                                    
                                }
                                
                                
                                if let commentCounts = item["commentsCount"] as? Int {
                                    object.commentCounts = commentCounts
                                    
                                }
                                if let postMedia = item["media"] as? [NSDictionary] {
                                    if postMedia.count > 0 {
                                        let icon_images = postMedia
                                        
                                        object.multiImageIcon = icon_images
                                        //                                                                                                                            self.multiImages_Icon.isHidden = false
                                        if let media = postMedia[0]["media"] as? String {
                                            object.image = media
                                        }
                                    }
                                    
                                }
                                
                                if let profile = item["profile"] as? NSDictionary {
                                    
                                    if profile.count > 0 {
                                        
                                        if let name = profile["name"] as? String {
                                            
                                            object.name = name
                                            
                                        }
                                        
                                        if let logo = profile["logo"] as? String {
                                            
                                            object.ava = logo
                                            
                                            
                                        }
                                    }
                                }
                                
                                object.text = item["postText"] as? String
                                object.name = item["name"] as? String
                                object.date = item["createdAt"] as? String
                                object.id = item["id"] as? Int
                                object.ava = item["logo"] as? String
                                object.commentCounts = item["commentsCount"] as? Int
                                object.interactionsCount = item["interactionsCount"] as? Int
                                object.allPages = item["allPages"] as? Int
                                
                                self.posts.append(object)
                                self.tableView.reloadData()
                                
                            }
                        }
                    }
                } catch {
                    Helper().showAlert(title: "JSON Error",message: error.localizedDescription,in: self)
                    return
                }
            }
        }.resume()
    }

最后是自定义数据源:

// MARK: - 表视图数据源

override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
    return posts.count
}

override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if thisPage < allPages && indexPath.row == posts.count - 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "loading")
        return cell!
        
    }else {
        
        let pictureUrl = posts[indexPath.row].image ?? ""
    
        if pictureUrl.isEmpty == true {
        
        //5)=> accessing the text cell from main.storyboard
         let cell = tableView.dequeueReusableCell(withIdentifier: "NoPicCell",for: indexPath) as! NoPicCell
        
        
        cell.fullNameLabel.text = posts[indexPath.row].name?.capitalized ??
            UserDefaults.standard.value(forKey: "name") as? String
        
        cell.fullNameLabel.textColor = .label
        
        let postText = posts[indexPath.row].text
        
        cell.postTextLabel.text = postText
        cell.postTextLabel.textColor = .label
        
        let dateString = posts[indexPath.row].date
        
        let formatterGet = DateFormatter()
        formatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        
        let date = formatterGet.date(from: dateString ?? "")
        
        let formatterShow = DateFormatter()
        formatterShow.dateFormat = "MMMM dd yyyy - HH:mm"
        
        cell.dateLabel.text = formatterShow.string(from: date ?? Date())
        
        let postStars = posts[indexPath.row].interactionsCount ?? 0
        
        cell.starCountTwo.text = "\(postStars )"
        cell.starCountTwo.textColor = .label
        
        let postComments = posts[indexPath.row].commentCounts ?? 0
        
        cell.commentCountOne.text = "\(postComments)"
        cell.commentCountOne.textColor = .label
        
        let avaPath = UserDefaults.standard.value(forKey: "logo") as? String
        
        let ava = posts[indexPath.row].ava
        
        Helper().downloadImage(from: (ava ?? avaPath)!,showIn: cell.avaImageViewNoPic,orShow: "user.png")
        
        // Rounded corners
        cell.avaImageViewNoPic.layer.cornerRadius = cell.avaImageViewNoPic.frame.width / 2
        cell.avaImageViewNoPic.clipsToBounds = true
        
        cell.commentsButton.tag = indexPath.row
        cell.starButtonTwo.tag = indexPath.row
        cell.optionButton.tag = indexPath.row
        
        pictures.append(UIImage())
        
        return cell

    } else {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "PicCell",for: indexPath) as! PicCell
        
        let postText = posts[indexPath.row].text
        cell.postTextLabel.text = postText
        cell.postTextLabel.textColor = .label
        
        cell.fullNameLabel.text = posts[indexPath.row].name?.capitalized ?? UserDefaults.standard.value(forKey: "name") as? String
        
        cell.fullNameLabel.textColor = .label
        
        let dateString = posts[indexPath.row].date
        
        let formatterGet = DateFormatter()
        formatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        
        let date = formatterGet.date(from: dateString!)
        
        let formatterShow = DateFormatter()
        formatterShow.dateFormat = "MMMM dd yyyy - HH:mm"
        
        cell.dateLabel.text = formatterShow.string(from: date!)
        
        let postStars = posts[indexPath.row].interactionsCount ?? 0
        
        cell.starCountPic.text = "\(postStars )"
        cell.starCountPic.textColor = .label
        
        let postComments = posts[indexPath.row].commentCounts ?? 0
        
        cell.commentCountOne.text = "\(postComments)"
        cell.commentCountOne.textColor = .label
        
        let ava = posts[indexPath.row].ava
        
        let avaPath = UserDefaults.standard.value(forKey: "logo") as? String
        
        Helper().downloadImage(from: (ava ?? avaPath)!,showIn: cell.avaImageViewPic,orShow: "user.png")
        
        // Rounded corners
        cell.avaImageViewPic.layer.cornerRadius = cell.avaImageViewPic.frame.width / 2
        cell.avaImageViewPic.clipsToBounds = true
        
        cell.commentsButton.tag = indexPath.row
        cell.starButtonTwo.tag = indexPath.row
        cell.optionButton.tag = indexPath.row

        let pictureString = posts[indexPath.row].image
        
        let pictureURL = URL(string: pictureString ?? "")
        
        
        cell.pictureImageView.kf.setImage(with: pictureURL)
        
        if timelinePosts.count != pictures.count {
            
        }else{
            print("Pic cashed")
            DispatchQueue.main.async {
                

            }
            
    }
        
        cell.commentsButton.tag = indexPath.row
        cell.starButtonTwo.tag = indexPath.row
        cell.optionButton.tag = indexPath.row
        
    return cell
        }
    }
}

willDisplay 方法:


override func tableView(_ tableView: UITableView,willDisplay cell: UITableViewCell,forRowAt indexPath: IndexPath) {
        if thisPage < allPages && indexPath.row == posts.count - 1 {
            thisPage = thisPage + 1
        loadPosts(page: thisPage,refresh: false)
        }
    }

解决方法

将重载行移出 for 循环

threading

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-