【问题标题】:Swift Table View taking too much time to load JSON dataSwift Table View 花费太多时间来加载 JSON 数据
【发布时间】:2020-10-12 10:11:27
【问题描述】:

通过 API 请求从 Web 获取的数据总数为 114。但是加载数据需要 10-15 秒。我尝试了 DispatchQueue() 但没有发现任何改进。 ViewDidLoad 和 JSON 解析代码:

func parseJSON()  {
    let url = URL(string: "https://api.alquran.cloud/v1/quran/ar.alafasy")
    guard url != nil else{
        print("URL Founr Nill")
        return
    }
    URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error == nil && data != nil{
            do{
                let response = try JSONDecoder().decode(Surah.self, from: data!)
                self.surahName = response.data.surahs
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                    self.tableView.tableFooterView = UIView(frame: .zero)
                }
            }catch{
                print(error)
            }
        }
    }.resume() 
}

表格查看代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:QuranAudioCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuranAudioCell
    let surah = surahName[indexPath.row]
    cell.nameLbl.text = surah.englishName
    cell.arabicNameLbl.text = surah.name
    return cell
}

【问题讨论】:

  • 您正在发出网络请求。您确定不是网络请求花费了这么长时间(而不是实际的 UI 更新)?
  • 其实我不确定
  • if error == nil && data != nil{ 上添加打印,检查“日期”所需的时间。可能是……如果你的连接不好,或者服务器很慢,那很正常,不是吗?
  • if error == nil && data != nil{ print("Total data: (data!)") .是的,这需要很多时间

标签: ios swift


【解决方案1】:

根据上面的代码,唯一可能会很慢的是您正在发出的网络请求。

您在 viewDidLoad 中的 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0) { 是相当无意义的 TBH

此时加快速度的唯一方法是调试网络调用。

  • 您的连接通常很慢吗? (尝试在终端 ping google.com)
  • 您与特定服务器的连接速度慢吗? (尝试在终端ping主机)
  • 您的服务器是否响应缓慢(尝试在 Web 浏览器中打开它或在终端中使用 curl 获取 JSON

【讨论】:

  • ping:来自 172.67.177.176 的 64 个字节:icmp_seq=3 ttl=56 time=103.488 ms
猜你喜欢
  • 2018-09-23
  • 1970-01-01
  • 2016-10-08
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2016-05-07
相关资源
最近更新 更多